Issue
I don't understand why my piece of code doesn't work. I would like to have an x axis with an interval of 1.
df['Dates'] = pd.to_datetime(df.Dates)
fig, ax = plt.subplots(figsize=(16, 9))
ax.bar(df['Dates'],
df['Score'],
color='blue',
width=2)
date_form = DateFormatter("%d/%m/%Y")
ax.xaxis.set_major_formatter(date_form)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
ax2=ax.twinx()
ax2.plot(df['Dates'],
df['Price'],
color = 'black')
plt.show()
Solution
Currently, ax
's date formatting just gets overridden by ax2.plot
, so you should apply the date formatter to ax2
instead of ax
. Also autofmt_xdate
is useful for rotating the date labels:
df['Dates'] = pd.to_datetime(df['Dates'])
fig, ax = plt.subplots(figsize=(16, 9))
ax.bar(df['Dates'], df['Score'], color='blue', width=1)
ax2 = ax.twinx()
ax2.plot(df['Dates'], df['Price'], color='black')
# apply the date formatting to ax2 instead of ax
date_form = DateFormatter('%d/%m/%Y')
ax2.xaxis.set_major_formatter(date_form)
ax2.xaxis.set_major_locator(mdates.DayLocator(interval=1))
# rotate the date labels
fig.autofmt_xdate(ha='center', rotation=90)
This is the output with some random data (in the future it's recommended to paste data as text so we can directly copy the real data):
Answered By - tdy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.