Python——柱状图(条形图、堆叠图)
目录
1 基本函数
bar(x, height, [width], **kwargs) #竖条形图 barh(x, height, [width], **kwargs) #横条形图
x:数据标签(横坐标);
height:个数或一个数组,条形的高度;
[width]:可选参数,一个数或一个数组,条形的宽度,默认为 0.8
2 竖条形图
import matplotlib.pyplot as plt # 解决plt中文显示问题 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False x = ('A', 'B', 'C', 'D', 'E') y = [1, 2, 3, 4, 5] plt.bar(x, y) plt.title('结果') plt.show()
3 横条形图
import matplotlib.pyplot as plt # 解决plt中文显示问题 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False x = ('A', 'B', 'C', 'D', 'E') y = [1, 2, 3, 4, 5] plt.barh(x, y) plt.title('结果') plt.show()
4 并列条形图
import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 数据 x = ('A', 'B', 'C', 'D', 'E') y1 = [10, 12, 8, 6, 7] y2 = [6, 7, 8, 9, 10] bar_width = 0.2 # 条形宽度 index_y1 = np.arange(len(x)) # y1条形图的横坐标 index_y2 = index_y1 + bar_width # y2条形图的横坐标 # 使用两次 bar 函数画出两组条形图 plt.bar(index_y1, height=y1, width=bar_width, color='#499c9f', label='y1') plt.bar(index_y2, height=y2, width=bar_width, color='#c76813', label='y2') plt.legend() #图例 plt.xticks(index_y1 + bar_width/2, x) # 标签+位置 plt.ylabel('数量') # 纵坐标轴标题 plt.title('结果') # 图形标题 plt.show()
5 添加标签
import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 数据 x = ('A', 'B', 'C', 'D', 'E') y1 = [10, 12, 8, 6, 7] y2 = [6, 7, 8, 9, 10] bar_width = 0.3 # 条形宽度 index_y1 = np.arange(len(x)) # y1条形图的横坐标 index_y2 = index_y1 + bar_width # y2条形图的横坐标 # 使用两次 bar 函数画出两组条形图 plt.bar(index_y1, height=y1, width=bar_width, color='#499c9f', label='y1') plt.bar(index_y2, height=y2, width=bar_width, color='#c76813', label='y2') index = np.arange(len(y1)) for a,b in zip(index,y1): #柱子上的数字显示 plt.text(a*1.02,b*1.02,'%.2f'%b,ha='center',va='bottom',fontsize=7); for a,b in zip(index+width*3,y2): plt.text(a*1.02,b*1.02,'%.2f'%b,ha='center',va='bottom',fontsize=7); plt.legend() # 显示图例 plt.xticks(index_y1 + bar_width/2, x) # 让横坐标轴刻度显示 waters 里的饮用水, index_male + bar_width/2 为横坐标轴刻度的位置 plt.ylabel('数量') # 纵坐标轴标题 plt.title('结果') # 图形标题 plt.show()
6 堆叠柱形图
import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = ('A', 'B', 'C', 'D', 'E') y1 = [10, 12, 8, 6, 7] y2 = [6, 7, 8, 9, 10] bar_width = 0.3 # 条形宽度 plt.bar(x, y1, bar_width, color = '#A65F58', label = 'y1') plt.bar(x, y2, bar_width, bottom = y1, # 堆叠在第一个上方 color = '#99886B', label = 'y2') plt.legend()
本文作者:Rshimmer
本文链接:https://www.cnblogs.com/Rshimmer/p/17364158.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
标签:
,
,
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步