【问题标题】:Adding labels from another variable to a single bar in a barchart将标签从另一个变量添加到条形图中的单个条形
【发布时间】:2020-07-28 07:00:39
【问题描述】:

我正在尝试将一个字符串变量添加到我的图表中,但我不知道如何将它放在栏中。 我的字符串变量叫做city。

ax.barh(df['date'].values, df['cases'].values, color= '#49cff3')
ax.text(0, 1.06, 'Number of Cases', transform=ax.transAxes, size=12, color='#777777')
ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
ax.xaxis.set_ticks_position('top')
ax.tick_params(axis='x', colors='#777777', labelsize=12)
ax.set_yticks([])
ax.grid(which='major', axis='x', linestyle='-')
ax.set_axisbelow(True)
ax.text(0, 1.15, 'Total Number of cases',
        transform=ax.transAxes, size=24, weight=600, ha='left', va='top')
plt.yticks()
plt.box(False)

这是我的输出

在此先感谢

编辑:我尝试添加 @JohanC 的解决方案并得到以下输出:

【问题讨论】:

  • ax.set_yticks(range(len(df))); ax.set_yticklabels(df['city'])
  • 我尝试了这个解决方案,它产生了一个空图表,所有城市都捆绑在角落里;我将图片添加到原始问题中。感谢您的帮助

标签: python pandas numpy matplotlib jupyter-notebook


【解决方案1】:

如果您不将日期设置为 y 轴,ax.set_yticks(range(len(df))) 后跟 ax.set_yticklabels(df['city']) 就可以了。

但更推荐的方法是直接使用城市作为 y 轴。刻度线的长度可以为零,因此它们会在不可见的情况下不断地指示刻度线标签的位置。

如果您希望日期作为 y 轴,并将标签放在条内,您可以通过循环放置文本。但是不显示日期就使用日期作为 y 轴并没有太大意义。

要反转 y 轴,使最小(或第一个)值位于顶部,请使用 ax.invert_yaxis()

由于帖子没有包含测试数据,下面的示例从创建一些随机数据开始。

import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np
import pandas as pd

df = pd.DataFrame({'date': pd.date_range('2020-01-01', periods=10),
                   'cases': np.random.randint(80, 200, 10),
                   'city': [f'City {i}' for i in range(1, 11)]})
fig, ax = plt.subplots()
ax.barh(df['date'], df['cases'], color='#49cff3')
ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
ax.xaxis.set_ticks_position('top')
ax.tick_params(axis='x', colors='#777777', labelsize=12)
ax.tick_params(axis='y', length=0)
# ax.set_yticks([]) # this would make the both the tick marks and their labels disappear
ax.grid(which='major', axis='x', linestyle='-')
for row in df.itertuples(index=False):
    ax.text(0, row.date, ' '+row.city, ha='left', va='center', color='crimson')
ax.invert_yaxis()
plt.box(False)
plt.tight_layout()
plt.show()

【讨论】:

  • 我知道我确实故意让它们不可见,因为我想要的是日期数据在 y 轴上,城市显示在栏内,因为我想知道4 月 3 日,大多数病例发生在纽约
猜你喜欢
  • 1970-01-01
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 2021-03-27
  • 1970-01-01
  • 2018-08-14
  • 1970-01-01
相关资源
最近更新 更多