如何在python中使用matplotlib设置x轴刻度标记标签?

时间:2019-01-27 07:51:12

标签: python matplotlib

我只希望使用python中的matplotlib在条形图中显示条形图的x标签,即在x轴上显示1992、1993、1994、1995而不是1990、1990.5、1991、1991.5等,这是它的作用默认情况下

我尝试使用此处建议的代码:Manipulating x axis tick labels in matplotlib 建议使用以下命令:ind = range(2,6); plt.xticks(ind,x)

import pandas as pd
import numpy as np

np.random.seed(12346)

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])
Y = 40000

import math

%matplotlib notebook

plt.figure()

std = df.std(axis = 1)
stderror = std/math.sqrt(df.shape[1])
marginoferror = stderror*1.96
print(df.mean(axis=1).iloc[0] - marginoferror.iloc[0])

def color_def(y,dataframe,mofe):
    color = []
    for i in range(0,dataframe.shape[0]):
        if (dataframe.mean(axis=1).iloc[i] - mofe.iloc[i] > y):
            color.append('darkred')
        elif (dataframe.mean(axis=1).iloc[i] + mofe.iloc[i] < y):
            color.append('darkblue')
        else:
            color.append('white')
    return(color)
x = df.index.values
plt.bar(df.index.values,df.mean(axis=1),yerr=marginoferror,align='center', color = color_def(Y,df,marginoferror),alpha=0.5, edgecolor = 'black',ecolor='black', capsize=10)

plt.axhline(y=Y)

ind = range(2, 6)    # the x locations for the groups
plt.xticks( ind, x)

当我使用这两行代码ind = range(2,6); plt.xticks(ind,x)时,可以在此链接上看到意外的结果: https://www.dropbox.com/s/0ciuix13nhdj5jz/HW3%20v0.1.jpg?dl=0

它不是格式正确的条形图,并且没有用1992、1993、1994和1995标记x轴。

当我取出这两行代码时: ind = range(2,6); plt.xticks(ind,x), 我确实得到了格式合理的条形图,只是带有笨拙的x轴标签

1 个答案:

答案 0 :(得分:0)

不确定数字2到5与您的数据有何关系。您的数据是1992 ... 1995,这是数据框的索引,因此

plt.xticks(df.index.values)

将准确勾选那些值。

相关问题