【matplotlib】2.条形图

条形图

  • plt.bar()
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)[source]

1.参数

参数 含义 类型
x x轴含义 sequence of scalars
height 对应的条形的高度 scalar or sequence of scalars
width 条形的宽 scalar or array-like, optional,默认0.8

2.例子

2.1 例1 普通条形图

import matplotlib.pyplot as plt
import numpy as np

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

plt.bar(x, height=y)
plt.show()

在这里插入图片描述

2.2 例2 x轴为字符串

import matplotlib.pyplot as plt
import numpy as np

x = ['a', 'b', 'c', 'd', 'e']
y = [10, 20, 30, 40, 50]

plt.bar(x, height=y)
plt.show()

在这里插入图片描述

2.3 并列条形图

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])   # 转换成array之后便于加width
y1 = [10, 20, 30, 40, 50]
y2 = [20, 40, 60, 80, 100]

plt.bar(x, height=y1, width=0.3)
plt.bar(x+0.3, height=y2, width=0.3)
plt.show()

在这里插入图片描述

2.4 水平条形图

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])  
y1 = [10, 20, 30, 40, 50]


# 其中添加最后一个orientation之后,水平方向的参数和竖直方向的参数就反过来了
# 绘图 x= 起始位置, bottom= 水平条的底部(左侧), y轴, height 水平条的宽度, width 水平条的长度
plt.bar(x=0, bottom=x, height=0.5, width=y1, orientation="horizontal")
plt.show()

在这里插入图片描述

2.5 叠加条形图

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])   # 转换成array之后便于加width
y1 = [10, 20, 30, 40, 50]
y2 = [20, 40, 60, 80, 100]

lt.bar(x, height=y1, width=0.3)
plt.bar(x, height=y2, width=0.3, bottom=y1)  # y1开始就行了
plt.show()

在这里插入图片描述

3.更高阶的条形图

除了上面那些之外,还有更多高级的条形图,不过有些可能不会经常用到。这些在官网上也都有例子。

比如:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章