Reputation: 5
I have 2 graphs that share the same X axis and are plotted on a single figure (i.e. one X and two y axis). The problem is that a time frame, shown on the shared X axis is overly detailed and displays days rather then months(which I would prefer).
[fig1, ax1 = plt.subplots()
color = 'tab:red'
ax1.set_xlabel('Months')
ax1.set_ylabel('Price', color=color)
ax1.plot(df\['2019'\]\['Price'\], color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
color = 'tab:blue'
ax2.set_ylabel('RSI', color=color) # we already handled the x-label with ax1
ax2.plot(RSI(df\['2019'\]\['Price'\]), color=color)
ax2.tick_params(axis='y', labelcolor=color)
fig.tight_layout()
plt.show()][1]
Expect X axis to display months rather than dates
Upvotes: 0
Views: 218
Reputation: 226
You can simply use the DateFormatter
function and apply it on the x-axis data.
I have created a solution using some sample data, replacing RSI with a "Sales" information.
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
#Sample Data
data = [['2019-03-20',10, 1000],['2019-04-04',22,543],['2019-11-17',13,677]]
df = pd.DataFrame(data,columns=['Date','Price','Sales'])
# DateFormatter object to use abbreviated version of month names
monthsFmt = mdates.DateFormatter('%b')
fig1, ax1 = plt.subplots()
color = 'tab:red'
ax1.set_xlabel('Months')
ax1.set_ylabel('Price', color=color)
ax1.plot(pd.to_datetime(df['Date'], infer_datetime_format=True), df['Price'], color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
color = 'tab:blue'
ax2.set_ylabel('Sales', color=color) # we already handled the x-label with ax1
ax2.plot(pd.to_datetime(df['Date'], infer_datetime_format=True), df['Sales'], color=color)
ax2.tick_params(axis='y', labelcolor=color)
# Apply X-axis formatting at the end
ax2.xaxis.set_major_formatter(monthsFmt)
fig1.tight_layout()
plt.show()
This leads to the following result:
Upvotes: 1
Reputation: 836
You can use the xticks
method, to set the locations and labels of the ticks in your graph. As an example:
plt.xticks( [1,2,3,4,5,6,7,8,9,10,11,12], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
Note that the first list is the locations of the ticks on the axis, and the second is the labels. From the attached image, it is impossible to understand the type or scope of your x-axis, but I hope the solution is.
Upvotes: 0