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

时间:2019-12-18 11:13:00

标签: python matplotlib bar-chart data-visualization

我正在尝试在条形图上绘制平均值的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()

finish-plot

1 个答案:

答案 0 :(得分:0)

您可以使用轴对象的<testheader>方法将x-ticks设置为x轴值的自定义数组。

<testbody>

enter image description here

相关问题