0
votes

I only want x-labels displayed for the bars in the bar chart using matplotlib in python i.e. 1992, 1993, 1994, 1995 instead of 1990, 1990.5, 1991, 1991.5, etc on the x-axis which is what it does by default

I've tried using the code suggested here: Manipulating x axis tick labels in matplotlib which suggests using this: 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)

When I use these 2 lines of code ind = range(2,6); plt.xticks(ind,x), the unexpected result can be seen at this link: https://www.dropbox.com/s/0ciuix13nhdj5jz/HW3%20v0.1.jpg?dl=0

which is not a nicely formatted bar graph and does not have the x-axis labeled with 1992, 1993, 1994 and 1995.

When I take these 2 lines of code out: ind = range(2,6); plt.xticks(ind,x), I do get a nicely formatted bar chart just with the clunky x-axis labeling

1

1 Answers

0
votes

Not sure how the numbers 2 to 5 would relate to your data. Your data is 1992 ... 1995, which is the index of the dataframe, hence

plt.xticks(df.index.values)

would tick exactly those values.