画条形图(bar)

    xiaoxiao2021-12-14  21

    条形图的绘制通过pyplot中的bar或者是barh来实现。

    bar默认是绘制竖直方向的条形图,也可以通过设置 orientation = "horizontal" 参数来绘制水平方向的。

    barn就是绘制水平方向的条形图

    绘制简单的条形图

    #!/usr/bin/python #coding: utf-8 import numpy as np import matplotlib.pyplot as plt x = np.arange(10) y = np.random.randint(10, 30, 10) # 画竖直方向的条形图 # plt.bar(left= x, height= y, width= 0.5, color = "red") # 画水平方向的条形图 # 注意两句话中有区别的地方 # plt.bar(left = 0, bottom= x, width= y, height= 0.5, color = "red", orientation = "horizontal") # 或者使用barh函数,不需要显示声明orientation = "horizontal" plt.barh(left = 0, bottom= x, width= y, height= 0.5, color = "red") plt.show()

    绘制并列的条形图

    #!/usr/bin/python #coding: utf-8 import numpy as np import matplotlib.pyplot as plt x = np.random.randint(10, 50, 20) y1 = np.random.randint(10, 50, 20) y2 = np.random.randint(10, 50, 20) r = 0.5 plt.bar(left= x, height= y1, width= 0.5, color = "red") # 通过设置 left 来设置并列显示 plt.bar(left = x + r, height = y2, width = 0.5, color = "blue") plt.show()

    绘制层叠的条形图

    #!/usr/bin/python #coding: utf-8 import numpy as np import matplotlib.pyplot as plt x = np.random.randint(10, 50, 20) y1 = np.random.randint(10, 50, 20) y2 = np.random.randint(10, 50, 20) # 设置y轴的显示范围 plt.ylim(0, 100) plt.bar(left = x, height = y1, width = 0.5, color = "red", label = "$y1$") # 设置一个底部,底部就是y1的显示结果,y2在上面继续累加即可。 plt.bar(left= x, height= y2, bottom= y1, width= 0.5, color = "blue", label = "$y2$") plt.legend() plt.show()

    转载请注明原文地址: https://ju.6miu.com/read-963295.html

    最新回复(0)