源代码如下:
import matplotlib.pyplot as plt
# 这两行代码解决 plt 中文显示的问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
waters = ('绿色', '蓝色', '红色', '白色', '黑色')
buy_number = [6, 7, 6, 1, 2]
#通过color可调节图的颜色,可设定颜色列表,这样条形图每条颜色可变
colorss = ['g','b','r','w','k']
#通过width变量可调整条形的宽度
width = 0.4 # the width of the bars
#通过label可对条形进行标签,必须与plt.legend()连用,给所有条形设置标签需用列表
plt.bar(waters, buy_number, width, color=colorss,label='hello')
plt.legend()
plt.title('颜色统计')
plt.show()
横向条形图就是将竖向条形图的bar函数改为barh函数
源代码如下:
import matplotlib.pyplot as plt
# 这两行代码解决 plt 中文显示的问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
waters = ('绿色', '蓝色', '红色', '白色', '黑色')
buy_number = [6, 7, 6, 1, 2]
#通过color可调节图的颜色,可设定颜色列表,这样条形图每条颜色可变
colorss = ['g','b','r','w','k']
#通过width变量可调整条形的宽度
width = 0.4 # the width of the bars
#通过label可对条形进行标签,必须与plt.legend()连用,给所有条形设置标签需用列表
plt.barh(waters, buy_number, width, color=colorss,label='hello')
plt.legend()
plt.title('颜色统计')
plt.show()
源代码如下:
import matplotlib.pyplot as plt
import numpy as np
# 这两行代码解决 plt 中文显示的问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
width = 0.4 # the width of the bars
#设置x轴标注
waters = ('绿色', '蓝色', '红色', '白色', '黑色')
#设置条形纵坐标
buy_number = [6, 7, 6, 1, 2]
buy_number1 = [1, 2, 3, 4, 5]
#设置条形横坐标
index_male = np.arange(len(waters)) # 男生条形图的横坐标
index_female = index_male + width # 女生条形图的横坐标
#通过color可调节图的颜色,可设定颜色列表,这样条形图每条颜色可变
colorss = ['g','b','r','w','k']
#通过width变量可调整条形的宽度
#通过label可对条形进行标签,必须与plt.legend()连用,给所有条形设置标签需用列表
#在并行条形图中,有几个并行就使用几次bar,需要特别标出height和width变量,第一个参数为横坐标
plt.bar(index_male, height=buy_number, width=width, color=colorss,label='hello')
plt.bar(index_female,height=buy_number1,width=width)
#可调节坐标刻度,显示更加美观
plt.xticks(index_male + width/2, waters)
plt.legend()
plt.title('颜色统计')
plt.show()
对于重叠条形图,可通过设置相同x值,不同y值表现。使用不同颜色显示,即使用两个bar函数。源代码如下:
import numpy as np
import matplotlib.pyplot as plt
plt.subplot(1, 1, 1)
fig = plt.figure()
plt.figure(figsize=(8, 6))
plt.rcParams['font.sans-serif'] = ['KaiTi']
plt.rcParams['axes.unicode_minus'] = False
x = np.array(["a", "b", "c", "d"])
y1 = np.array([8566, 5335, 7610, 6482])
y2 = np.array([4283, 2667, 3655, 3241])
plt.bar(x, y1, width=0.3, label="1")
plt.bar(x, y2, width=0.3, label="2")
plt.title("xxx", loc="center")
plt.grid(False)
plt.legend(loc="upper center", ncol=2)
plt.show()
参考博客:https://blog.csdn.net/robert_chen1988/article/details/100047692