matplotlib(三)散點圖和條形圖

散點圖

簡單示例

from matplotlib import pyplot as plt
plt.rc('font', family='Microsoft YaHei', size=18) 
y_3 = [18,16,19,20,21,16,19,22,24,23,18,23,25,22,23,25,26,28,27,24,19,26,24,29,30,31,21,28,33,32,34]
y_10 = [34,33,32,34,31,29,25,28,26,29,24,25,23,25,24,23,22,19,23,22,16,26,25,20,16,18,19,16,18,16,16]

x = range(1,32)
plt.scatter(x,y_3)

plt.show()

簡單示例

a.繪製散點圖

plt.scatter(x,y_3)

b.x軸y軸刻度值,描述信息,圖例

from matplotlib import pyplot as plt
plt.rc('font', family='Microsoft YaHei', size=18) 
plt.figure(figsize=(20,8),dpi=80)

x_3 = range(1,32)
x_10 = range(51,82)

x_3_10 = list(x_3) + list(x_10)
x_string = ['3月{}號'.format(i) for i in range(1,32) ]
x_string += ['10月{}號'.format(i) for i in range(1,32)]

plt.xticks(list(x_3_10)[::3],x_string[::3],rotation=45)

plt.scatter(x_3,y_3,label='3月份')
plt.scatter(x_10,y_10,label='10月份')

#描述信息
plt.xlabel('時間')
plt.ylabel('氣溫 單位(℃)')
plt.title('3月和10月氣溫變化圖')

#添加圖例
plt.legend(loc='upper left')

plt.show()

複雜示例

條形圖

離散數據:個數據之間沒什麼關係 (ps:直方圖條與條之間無間隔,而條形圖有。)

簡單示例

x = ['A','B','C','D','E','F','G']
y = [21,22,13,2,5,34,23]

plt.figure(figsize=(20,8),dpi=80)

#繪製條形圖
plt.bar(range(len(x)),y,width = 0.3)
 
x_string = ['{}'.format(i) for i in x]
plt.xticks(range(len(x)),x_string)

plt.xlabel('姓名')
plt.ylabel('收入 單位(k元)')
plt.title('個人收入表')

plt.show()

簡單示例

a.繪製條形圖

plt.bar(range(len(x)),y,width = 0.3)

width : 柱狀圖的寬度
color:選擇柱狀圖的顏色

b.繪製橫向條形圖

x = ['A','B','C','D','E','F','G']
y = [21,22,13,2,5,34,23]

plt.figure(figsize=(20,8),dpi=80)

#繪製橫着的條形圖
plt.barh(range(len(x)),y,height = 0.3,color = 'orange')
 
x_string = ['{}'.format(i) for i in x]
plt.yticks(range(len(x)),x_string)

plt.ylabel('姓名')
plt.xlabel('收入 單位(k元)')
plt.title('個人收入表')

plt.grid(alpha = 0.4)
plt.show()

橫向條形圖

#不同電影三天的對比圖
x = ['天降之物','喜洋洋與灰太狼','鬼滅之刃']
y_1 = [14,4,15]
y_2 = [15,2,17]
y_3 = [10,1,14]

plt.figure(figsize=(20,8),dpi=80)

bar_height = 0.2

_y_1 = range(len(x))
_y_2 = [i + bar_height for i in _y_1]
_y_3 = [i + bar_height*2 for i in _y_1]

#繪製橫着的條形圖
plt.barh(_y_1,y_1,height = bar_height,label='15號')
plt.barh(_y_2,y_2,height = bar_height,label='16號')
plt.barh(_y_3,y_3,height = bar_height,label='17號')

#y軸刻度顯示
plt.yticks(_y_2,x)

plt.ylabel('電影名')
plt.xlabel('票房 單位(萬元)') 
plt.title('三日內電影票房對比表')

#圖例
plt.legend(loc='upper right')

#網格
plt.grid(alpha = 0.4)
plt.show()

對比條形圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章