Issue
How can I plot bar and line charts together with dates in the x axes? I tried the following code, but if I am not commenting line 13 the dates in the x axes do not have a rotation (90). How can I achieve the correct rotation and the dates formatted (Year-Month-Day) without hours and minutes?
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
x_axis = ['2020-12-28', '2021-01-04', '2021-01-11', '2021-01-18',
'2021-01-25', '2021-02-01', '2021-02-08', '2021-02-15',
'2021-02-22', '2021-03-01']
width = .35 # width of a bar
m1_t = pd.DataFrame({
'2-up' : [1,2,3,3,3,2,2,2,5,9],
'2-down' : [2,7,6,7,7,6,5,4,2,4],
'close' : [120,170,160,172,177,166,155,144,122,144]})
m1_t[['2-up','2-down']].plot(kind='bar', width = width)
m1_t['close'].plot(secondary_y=True) #if I decomment this line, the plt.xticks rotation is no more
working? Why?
ax = plt.gca()
plt.xlim([-width, len(m1_t['2-up'])-width])
x_axis = df_strat_out.index
ax.set_xticklabels(x_axis)
plt.xticks(rotation = 90)
plt.show()
Solution
You can make x_axis
as the index, and use rot
option:
x_axis = ['2020-12-28', '2021-01-04', '2021-01-11', '2021-01-18',
'2021-01-25', '2021-02-01', '2021-02-08', '2021-02-15',
'2021-02-22', '2021-03-01']
width = .35 # width of a bar
# pass the index here
m1_t = pd.DataFrame({
'2-up' : [1,2,3,3,3,2,2,2,5,9],
'2-down' : [2,7,6,7,7,6,5,4,2,4],
'close' : [120,170,160,172,177,166,155,144,122,144]}, index=x_axis)
m1_t[['2-up','2-down']].plot(kind='bar', width = width)
m1_t['close'].plot(secondary_y=True, rot=90)
# this is not needed
# ax = plt.gca()
plt.xlim([-width, len(m1_t['2-up'])-width])
# neither are these
# ax.set_xticklabels(x_axis)
# plt.xticks(rotation = 90)
plt.show()
OUtput:
Answered By - Quang Hoang
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.