python - 如何将条形图标签移动到 Y 轴?
问题描述
我想在 Y 轴上标记条形标签,而不是条形图的顶部。有没有办法做到这一点?
我有一段很长的代码来重新创建这个情节,所以只复制它的一部分。我唯一的想法是通过 ax.patches 一个一个来做。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(32000,200000,3650),
np.random.normal(43000,100000,3650),
np.random.normal(43500,140000,3650),
np.random.normal(48000,70000,3650)],
index=[1992,1993,1994,1995])
df
....
bar_plot = plt.bar(df.index, df.mean(axis=1),yerr=upper, edgecolor='indigo', color=color)
for i in ax.patches:
ax.text(i.get_x()+0.2, i.get_height()-5.8, \
str(round((i.get_height()), 1)), fontsize=14, color='darkblue')
解决方案
为了也显示 y 轴上的高度,可以在这些位置引入较小的 y 刻度。或者,可以在此处绘制网格线。
对于不干扰主要 y 刻度标签的次要 y 刻度标签,一种可能性是使刻度更大,从而将刻度向左移动。
其他可能性是完全删除主要刻度(plt.yticks([])
),或在右侧绘制任一刻度。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FixedLocator, FormatStrFormatter
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(32000, 200000, 3650),
np.random.normal(43000, 100000, 3650),
np.random.normal(43500, 140000, 3650),
np.random.normal(48000, 70000, 3650)],
index=[1992, 1993, 1994, 1995])
means = df.mean(axis=1)
bar_plot = plt.bar(df.index, means, edgecolor='indigo',
color=[plt.cm.inferno(i / df.shape[0]) for i in range(df.shape[0])])
plt.xticks(df.index)
ax = plt.gca()
ax.yaxis.set_minor_locator(FixedLocator(means))
ax.yaxis.set_minor_formatter(FormatStrFormatter("%.2f"))
ax.tick_params(axis='y', which='minor', length=40, color='r', labelcolor='r', labelleft=True)
plt.grid(axis='y', which='minor', color='r', ls='--')
plt.tight_layout()
plt.show()
推荐阅读
- api - 从 youtube 数据 API 收到 403 错误
- oracle - 带有 GT 的 XMLTRANSFORM;操作员
- windows - 批处理文件检查文件夹内容并重新启动打印后台处理程序不起作用
- javascript - 一起使用对象轨迹和像素数据,没有得到我希望的结果?
- php - php file_get_contents('php://input') 返回 null
- pandas - 如何将 df1 和 df2 合并到 df3 中?
- amazon-web-services - 在 Amazon QuickSight 中将时间戳字段转换为日期字符串
- asp.net - 如何增加executionTimeout
- excel - 阵列不准确
- python - 不使用 numpy 计算协方差矩阵