【问题标题】:Get the value printed on top of bar chart using python and matplotlib?使用 python 和 matplotlib 获取打印在条形图顶部的值?
【发布时间】:2019-05-09 07:59:47
【问题描述】:

我正在尝试使用条形顶部的值打印图表,该值将根据图表自动更改。我正在使用以下代码:

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.barh(x='Class',y=class_sum_sort).invert_yaxis()
plt.title('My Dynamic Graphs')
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 添加为红色吗? 谁能帮我解决这个问题?

【问题讨论】:

  • 我不明白您所说的“条形图顶部的值将根据图表自动更改”是什么意思
  • 您的意思是 在每个水平条的顶部 使用 plot.barh( ) 吗?你的意思是从哪个会根据图表自动改变autolabel机制?

标签: python python-3.x matplotlib


【解决方案1】:

您可以遍历条形并设置文本和颜色。

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()

【讨论】:

  • 可能 OP 意味着在 h 条顶部的值标记而不是在条的边缘末端的右侧进行注释。
猜你喜欢
  • 1970-01-01
  • 2022-11-17
  • 2022-07-06
  • 2017-03-25
  • 2018-04-03
  • 2017-07-29
  • 1970-01-01
  • 2019-01-25
相关资源
最近更新 更多