簡體   English   中英

如何在python中使用matplotlib設置x軸刻度標記標簽?

[英]How to set x-axis tick mark labels using matplotlib in python?

我只希望在python中使用matplotlib在條形圖中為條形圖顯示x標簽,即1992、1993、1994、1995而不是1990、1990.5、1991、1991.5等在x軸上顯示,這是默認情況下的操作

我嘗試使用這里建議的代碼: 在matplotlib中操縱x軸刻度標簽 ,建議使用以下代碼: ind = range(2,6); plt.xticks(ind,x) 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) ind = range(2,6); plt.xticks(ind,x) ,可以在此鏈接上看到意外的結果: https : ind = range(2,6); plt.xticks(ind,x) =0

它不是格式良好的條形圖,並且沒有標有1992、1993、1994和1995的x軸。

當我取出這兩行代碼時: ind = range(2,6); plt.xticks(ind,x) ind = range(2,6); plt.xticks(ind,x) ,我確實得到了格式很好的條形圖,只是帶有笨拙的x軸標簽

不確定數字2到5與您的數據有何關系。 您的數據是1992 ... 1995,這是數據框的索引,因此

plt.xticks(df.index.values)

會准確地勾選這些值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM