是否使用python和matplotlib将值打印在条形图顶部?
我正在尝试打印带有条形图顶部值的绘图,该值将根据图形自动更改。我正在使用以下代码:是否使用python和matplotlib将值打印在条形图顶部?,python,python-3.x,matplotlib,Python,Python 3.x,Matplotlib,我正在尝试打印带有条形图顶部值的绘图,该值将根据图形自动更改。我正在使用以下代码: 将熊猫作为pd导入 将matplotlib.pyplot作为plt导入 hsif=pd.read\u excel('C:\\Users\\ans\\Desktop\\test.xlsx') class_sum=hsif.groupby('class')['Value'].sum() class\u sum\u sort=class\u sum.sort\u值(升序=False) ax=class\u sum\u
将熊猫作为pd导入
将matplotlib.pyplot作为plt导入
hsif=pd.read\u excel('C:\\Users\\ans\\Desktop\\test.xlsx')
class_sum=hsif.groupby('class')['Value'].sum()
class\u sum\u sort=class\u sum.sort\u值(升序=False)
ax=class\u sum\u sort.plot.barh(x='class',y=class\u sum\u sort).invert\u yaxis()
plt.title(“我的动态图”)
plt.xlabel('Value',fontsize=20)
plt.ylabel('Class',fontsize=20)
plt.show()
excel文件包含以下数据:
+----------+---------+
| Class | Value |
+----------+---------+
| Six | 3763 |
| Six | 2570 |
| Six | 1123 |
| Six | 901 |
| Seven | 12210 |
| Seven | 10384 |
| Seven | 3188 |
| Seven | 2592 |
| Seven | 1723 |
| Seven | 1011 |
+----------+---------+
我们是否可以将特定于Six
的颜色添加为橙色,将Seven
添加为红色?
有人能帮我吗?你可以循环浏览这些条,设置文字和颜色
import pandas as pd
import matplotlib.pyplot as plt
hsif = pd.read_excel('C:\\Users\\ans\\Desktop\\test.xlsx')
class_sum = hsif.groupby('Class')['Value'].sum()
class_sum_sort = class_sum.sort_values(ascending=False)
ax = class_sum_sort.plot(kind="barh", fontsize=13)
ax.set_title('My Dynamic Graphs')
ax.set_xlabel('Value', fontsize=20)
ax.set_ylabel('Class', fontsize=20)
for i in ax.patches:
ax.text(i.get_width(), i.get_y()+.3, str(i.get_width()), fontsize=13)
ax.patches[0].set_color("red")
ax.patches[1].set_color("orange")
ax.invert_yaxis()
plt.tight_layout()
plt.show()
我不明白您所说的“在条形图顶部的值将根据图形自动更改的绘图”是什么意思,您是说使用
plot.barh()
,在每个水平条的顶部进行绘图吗?您的意思是根据图形自动更改的是autolabel
mechanism吗?OP可能意味着在h条顶部标注值,而不是在条边末端的右侧标注。