简体   繁体   English

条形图上的自定义 xticks 标签 (matplotlib)

[英]Custom xticks labels on a bar chart (matplotlib)

Im trying to plot the 95% confidence interval for the mean on a bar chart.我试图在条形图上绘制平均值的 95% 置信区间。 The bar colors are set based on the horizontal line value.条形颜色是根据水平线值设置的。 So bars is colored red if they are definitely above this value (given the confidence interval), blue if they are definitely below, or white if they contain this value.因此,如果条形绝对高于此值(给定置信区间),则条形为红色,如果肯定低于此值,则为蓝色,如果包含此值,则为白色。

The finished plot contains too many xticks labels.完成的绘图包含太多 xticks 标签。 I tried using a few methods like xaxis.set_major_locator and plt.xticks(range(len(df.index)), df.index) but it all turned out bad.我尝试使用一些方法,如xaxis.set_major_locatorplt.xticks(range(len(df.index)), df.index)但结果都不好。 I think it's the problem with my color mask setting, but I cant figure how to fix it.我认为这是我的颜色蒙版设置的问题,但我不知道如何解决它。

Really appreciate any help and advice.非常感谢任何帮助和建议。 Thanks!谢谢!

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

完成情节

You can set the x-ticks to a custom array of x-axis values using the set_xticks method of the axis object.您可以使用轴对象的set_xticks方法将 x-ticks 设置为 x 轴值的自定义数组。

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM