1

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.

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Especially for such a detailed explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.