Matplotlib的绘图功能
文章目录
1.条形图
import matplotlib.pyplot as plt
data = [5, 20, 15, 25, 10]
plt.bar(range(len(data)), data)
plt.show()
bar(left, height, width=0.8, bottom=None, **kwargs)
可以通过增加关键字对条形图进行修饰:
-
颜色
facecolor(或fc):用于设置柱体的颜色
通过 color 关键字参数 可以一次性设置多个颜色,color是一个数组
-
描边
- edgecolor 或 ec:描边的颜色,如white,black,blue
- linestyle 或 ls: 描边的样式,如 “-” , “–”;
- linewidth 或 lw:描边的宽度 :
-
填充
hatch :hatch的值用于设置填充条形图的图形,如 “X”, “o” ,"/" ;
注意:hatch的长个数表示填充的密度,如"“表示用”/"密集得填充
-
误差线
yerr: 定义误差的浮动的绝对值 error_kw: 误差线关键字,是一个字典 关键字有: ecolor:误差线的颜色 elinewidth: 误差线的宽度,即粗细 capsize: 误差线帽子的长度
-
图例位置
pyplot.legend(**ky) #loc: 可选'best','upper left','bottom right' 等 #bbox_to_anchor=(0.2, 1),以左下角为为原点,调整位置 #bbox_transform=ax.transAxes #frameon: 图例是否有边框 #下面的操作由于修改边框的颜色 leg = plt.legend() leg.get_frame().set_edgecolor('b')
-
合并图例
#得到坐标轴1图例的句柄和标签值 handles_1, labels_1 = ax1.get_legend_handles_labels() #得到坐标轴2图例的句柄和标签值 handles_2, labels_2 = ax2.get_legend_handles_labels() #关键字传入,传入label(一个数组)参数可以改变图例的标签值 plt.legend(handles=handles_1 + handles_2, bbox_to_anchor=(0.1, 1))
-
设置刻度线标签(tick label)
import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] labels = ['Tom', 'Dick', 'Harry', 'Slim', 'Jim'] plt.bar(range(len(data)), data, tick_label=labels) plt.show()
示例:
import matplotlib.pyplot as plt
labels = [0.3, 0.5, 1.0, 1.5, 3.0]
bottom_means = [20, 80, 160, 250, 400]
top_means = [210, 250, 1200, 1500, 2600]
top_std = [20, 40, 80, 200, 500]
width = 0.15 # the width of the bars: can also be len(x) sequence
#subplots是将多个图画到同一个平面上得工具,在matlab也有同样的函数
fig, ax = plt.subplots()
ax.bar(labels, bottom_means, width, color='white', edgecolor='black', ls='-', lw=1, hatch='', label='PFOA in water')
ax.bar(labels, top_means, width, color='white', edgecolor='black', ls='-', lw=1, yerr=top_std, bottom=bottom_means,
hatch='xx',
label='PFOA on SS')
#设置y轴上得标签值
ax.set_ylabel('PFOA amount (g)')
#设置图标的标题
ax.set_title('Initial PFOA concentration (mg/L)')
#设置图例,loc=location,指的是图例的位置
ax.legend(loc='upper left')
plt.show()
绘制其他样式的柱形图
-
水平的条形图
import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] plt.barh(range(len(data)), data) plt.show()
-
正负条形图
import numpy as np
import matplotlib.pyplot as plt
a = np.array([5, 20, 15, 25, 10])
b = np.array([10, 15, 20, 15, 5])
plt.barh(range(len(a)), a)
plt.barh(range(len(b)), -