Reputation: 1133
I have a pandas df as follows:
Date Col1 Col2
2022-01-01 5 10000
2022-02-01 7 65000
2022-03-01 10 9500
I want to create a plot such that the xaxis
is Date
and the Col1
is a barplot and Col2
is a lineplot.
How can I do this in python? Open to try seaborn or matplotlib.
The Date
is a pd.datetime
object.
Upvotes: 1
Views: 3674
Reputation: 41427
Since the two scales are vastly different, create a secondary y-axis.
Since bar plots are categorical, seaborn converts the x
dates to ordinal ticks. That means matplotlib date formatters will no longer work on them, so it's better to format the date strings beforehand, e.g., dt.date
or dt.strftime
.
Also since seaborn changes the x-axis to ordinal ticks, it's simplest to create the lines with a pointplot
(but if you really want to use a lineplot
, reset the index and set x
to the numeric range).
fig, ax1 = plt.subplots()
ax2 = ax1.twinx() # secondary y-axis
df['Date'] = df['Date'].dt.date # or dt.strftime('%Y-%m-%d')
sns.barplot(x='Date', y='Col1', data=df, ax=ax1) # on primary ax1
sns.pointplot(x='Date', y='Col2', color='#333', data=df, ax=ax2) # on secondary ax2
# sns.lineplot(x='index', y='Col2', color='#333', data=df.reset_index(), ax=ax2)
Upvotes: 3