Matpltlib barh data label
时间: 2024-10-04 13:04:52 浏览: 38
Matplotlib是一个非常流行的Python数据可视化库,其中`barh`函数用于创建水平条形图。当你想要展示数据的不同类别,并通过高度表示数值大小时,可以使用它。
当你调用`barh()`函数时,需要提供一系列的数据值作为输入,以及一组标签,对应每个条形图的高度。例如:
```python
import matplotlib.pyplot as plt
# 假设我们有数据
data = [50, 60, 70, 80, 90]
categories = ['A', 'B', 'C', 'D', 'E']
# 创建水平条形图
plt.barh(categories, data)
# 添加横轴和纵轴标签
plt.xlabel('数值')
plt.ylabel('类别')
# 设置图例(如果有必要)
plt.title('各分类数值对比')
plt.legend(['数值'])
# 显示图形
plt.show()
```
在这个例子中,`categories`列表是水平方向的刻度(label),`data`列表决定了每个条形的高度。通过这种方式,你可以清晰地看到各个类别的相对数值。
相关问题
Matplotlib barh data annotate
Matplotlib是一个广泛使用的Python数据可视化库,其中`barh`函数用于创建水平条形图。当你想要在绘制的条形图上添加注释时,可以使用`annotate`方法。
`annotate`函数允许你在图表的特定位置添加文本标签,通常包含数据点的具体值或者额外的信息。其基本语法如下:
```python
import matplotlib.pyplot as plt
import numpy as np
# 假设我们有数据
x = ['A', 'B', 'C', 'D']
y = [10, 25, 17, 32]
fig, ax = plt.subplots()
bars = ax.barh(x, y, color='blue')
# 添加注解,例如添加每个条形的高度值
for i, bar in enumerate(bars):
ax.annotate(str(y[i]), xy=(bar.get_width(), bar.get_y()), textcoords='offset points', ha='center', va='bottom')
plt.show()
```
在这个例子中,`xy`参数指定注解的位置,通常是基于条形的位置;`textcoords`设置注解相对于图形元素的坐标系统;`ha`和`va`分别控制文本的水平和垂直对齐方式。
fig, ax = plt.subplots(figsize=(15, 12))female_income = data[data["Gender"]=="Female"]["Income"]male_income = data[data["Gender"]=="Male"]["Income"]ax.barh(data["MaritalStatus"], female_income, height=0.7, label="Female")ax.barh(data["MaritalStatus"], male_income, height=0.7, left=female_income, label="Male")ax.set_xlabel("Income")ax.legend()plt.show()
这段代码使用了Matplotlib库绘制了一个水平条形图,用于比较不同婚姻状况下男性和女性的收入情况。
首先,通过plt.subplots()函数创建一个画布fig和一组子图ax,指定了画布的大小为(15,12)。
接着,从数据集中筛选出性别为女性和男性的数据,并分别赋值给female_income和male_income。
然后,使用ax.barh()函数分别绘制了女性和男性的水平条形图,其中参数data["MaritalStatus"]表示婚姻状况是x轴,female_income和male_income分别表示女性和男性的收入是y轴,height和left分别表示条形图的高度和水平位置。
最后,使用ax.set_xlabel()函数设置x轴的标签为“Income”,使用ax.legend()函数添加图例,并通过plt.show()函数显示图形。
阅读全文
相关推荐















