Histogram: How can I get the same date format on the x axis as in the time series chart?

I have a pandas random number framework where the index is of type dtype='datetime64[ns] . At the end of the question you will find reproducible code.

enter image description here

When I draw this with ax.dfplot() , I get a beautifully formatted x axis as follows:

enter image description here

I would like to make a diagram from this instead, but when I use ax = df.plot(kind = 'bar') , the x axis gets messed up:

enter image description here

How can i change this?

Thanks for any suggestions!

Reproducible code for the input data frame and the first two graphs:

 import pandas as pd import numpy as np import matplotlib.dates as mdates # Dataframe with 1 or zero np.random.seed(123) rows = 10 df = pd.DataFrame(np.random.randint(90,110,size=(rows, 2)), columns=list('AB')) datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist() df['dates'] = datelist df = df.set_index(['dates']) df.index = pd.to_datetime(df.index) print(df.head(10)) #print(df) # Option 1 # -Time series # -kind is undefined title = 'time series' ax = df.plot(title = title, fontsize = 10) #ax.legend().set_visible(legend) # Option 2 # -Bar chart # -kind is defined as bar title = 'Bar' ax = df.plot(title = title, fontsize = 10, kind = 'bar') 

Here is what I have tried so far:

Here is a somewhat similar question, but I am having problems with the playable fragment provided there. Perhaps the problem is with the version, since she is several years old?

I was also able to at least improve the format using the suggestions here :

 title = 'Bar' ax = df.plot(title = title, fontsize = 10, kind = 'bar') xtl=[item.get_text()[:10] for item in ax.get_xticklabels()] _=ax.set_xticklabels(xtl) 

enter image description here

I had high hopes for suggestions here , as it seemed that at least I could only display months to the mdates.DateFormatter('%d') (using m instead). But I am having problems with the results:

 title = 'Bar' ax = df.plot(title = title, fontsize = 10, kind = 'bar') myFmt = mdates.DateFormatter('%d') ax.xaxis.set_major_formatter(myFmt) 

I only get this:

enter image description here

+5
source share

Source: https://habr.com/ru/post/1270731/


All Articles