【问题标题】:Custom xticks labels on a bar chart (matplotlib)条形图上的自定义 xticks 标签(matplotlib)
【发布时间】:2020-04-10 22:25:49
【问题描述】:

我试图在条形图上绘制平均值的 95% 置信区间。 条形颜色是根据水平线值设置的。因此,如果条形绝对高于此值(给定置信区间),则条形为红色,如果绝对低于此值,则为蓝色,如果包含此值,则为白色。

完成的绘图包含太多 xticks 标签。我尝试使用xaxis.set_major_locatorplt.xticks(range(len(df.index)), df.index) 等一些方法,但结果都很糟糕。 我认为这是我的颜色蒙版设置的问题,但我不知道如何解决它。

非常感谢任何帮助和建议。谢谢!

import pandas as pd
import numpy as np
from scipy import stats
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])

mean = df.mean(axis = 1)
std = df.std(axis = 1)
n = len(df.columns)

yerr = []
for index, row in df.iterrows():
    yerr.append(stats.sem(row)*stats.t.ppf((1+0.95)/2, n-1))

theline = 42000
high_mask = theline > (mean+yerr)
low_mask = theline < (mean-yerr)
equal_mask = ((mean-yerr) <= theline) & (theline <= (mean+yerr))

plt.figure()
plt.bar(df.index[high_mask.values], mean.iloc[high_mask.values], alpha=0.5, color='blue')
plt.bar(df.index[low_mask.values], mean.iloc[low_mask.values], alpha=0.5, color='red')
plt.bar(df.index[equal_mask.values], mean.iloc[equal_mask.values], alpha=0.5, color='grey')
plt.errorbar(df.index, mean, yerr=yerr, fmt=".", color="k")
plt.axhline(y=theline, color="grey", alpha=0.7)
# plt.gca().set_xticklabels(df.index)
# plt.xticks(range(len(df.index)), df.index)
plt.show()

【问题讨论】:

  • 这个灵魂作品plt.xticks(df.index)
  • 谢谢。这也适用于我。不知道为什么我错过了这个!

标签: python matplotlib bar-chart data-visualization


【解决方案1】:

您可以使用轴对象的set_xticks 方法将 x 刻度设置为自定义的 x 轴值数组。

ax = plt.gca()
ax.set_xticks([1992, 1993, 1994, 1995])

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多