
简单垂直条形图、简单水平条形图、水平交错条形图、子图画法
python+matplotlib绘图线条类型和颜色选择_Python_syyyy712的博客-CSDN博客blog.csdn.net

条形图
- 简单垂直条形图
- 字体与坐标轴设置(避免中文乱码、坐标轴不能正常显示符号)
- 方法1:通过rc参数
- 方法2:https://blog.csdn.net/mr_muli/article/details/89485619
import matplotlib.pyplot as plt
% matplotlib inline
# rc参数处理
plt.rcParams['font.sans-serif'] = 'simhei'
plt.rcParams['axes.unicode_minus'] = False
- 绘图
- plt.bar(x横坐标值,y纵坐标值, align, color, alpha透明度)
- plt.ylabel('name', fontsize=)坐标轴名称
- plt.title图标题
- plt.xticks(位置,标签)刻度标签
- plt.ylim坐标范围
- plt.text(横向位置(柱子),纵向位置,标签内容,ha)添加数值标签
- 参数ha水平对齐方式:[ ‘center’ | ‘right’ | ‘left’ ]
# 绘图
plt.bar(range(4), GDP, align = 'center', color = 'deeppink', alpha = .7)
plt.ylabel('GDP', fontsize = 18)
plt.xlabel('city', fontsize = 18)
plt.title('四个直辖市GDP')
plt.xticks(range(4), ['北京','上海','天津','重庆'])
plt.ylim([5000,15000])
# 添加数值标签
for x,y in enumerate(GDP):
plt.text(x, y+100, '%s' %round(y,1), ha = 'center')

2. 简单水平条形图
- 绘图
- plt.barh(x(会成图里的纵轴),y(成图里的横轴))
- plt.text(横向位置,纵向位置(柱子),va = )
- va垂直对齐方式:[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
price = [39.5,39.9,45.4,38.9,33.34]
plt.barh(range(5),price,align = 'center', color = 'blue', alpha = .7)
plt.xlabel('价格')
plt.title('不同平台书价格')
plt.yticks(range(5),['亚马逊','当当网','中国图书网','京东','天猫'])
plt.xlim([32,47])
for x,y in enumerate(price):
plt.text(y+0.1, x, '%s' %y, va = 'center')

3. 水平交错条形图
- 参数width:柱子宽度和柱子位置要算好,不然会重叠
- 参数label,从而可以用plt.legend()显示图例
Y2016 = [15600,12700,11300,4270,3620]
Y2017 = [17400,14800,12000,5200,4020]
labels = ['北京','上海','香港','深圳','广州']
bar_width = 0.35
# 绘图
plt.bar(np.arange(5), Y2016, label = '2016', color = 'steelblue', alpha = 0.7, width = bar_width);
plt.bar(np.arange(5)+bar_width, Y2017, label= '2017', color = 'indianred', alpha = 0.7, width = bar_width);
plt.xlabel('Top5 city');
plt.ylabel('家庭数量');
plt.title('亿万财富家庭数Top5城市分布');
plt.xticks(np.arange(5)+bar_width, labels);
for x,y in enumerate(Y2016):
plt.text(x,y+100, '%s' %y, ha = 'center')
for x,y in enumerate(Y2017):
plt.text(x+bar_width, y+100, '%s' %y, ha = 'center')
plt.legend();

子图画法
- 先plt.figure()
- plt.subplot(121) 画1*2的第一张图
In [4]: x = np.arange(6)
In [5]: y = np.random.randint(0,10,6)
In [6]: y
Out[6]: array([8, 1, 3, 2, 8, 4])
In [7]: plt.figure()
Out[7]: <matplotlib.figure.Figure at 0x1fc5c9ec358>
In [8]: plt.subplot(121)
Out[8]: <matplotlib.axes._subplots.AxesSubplot at 0x1fc5ca0d048>
In [9]: plt.bar(x,y,width=0.5,color = ['r','g','b'])
Out[9]: <Container object of 6 artists>
In [10]: plt.subplot(122)
Out[10]: <matplotlib.axes._subplots.AxesSubplot at 0x1fc5ccd87b8>
In [11]: plt.bar(x,y,color = ['r','g','b'], alpha = 0.5)
Out[11]: <Container object of 6 artists>
In [12]: plt.show()

参考:
https://www.kesci.com/home/project/59ed8d7418ec724555a9b4c0
https://www.jianshu.com/p/47dfbe43dae1