0

When I plot a graph, the bargraph's date changes to 1970's while the overlaid lineplot remains correct. If I remove the code from twinx() onward, the bargraph displays correctly with the correct date range. I have also tried removing the x argument from the lineplot, but it only results in the lineplot not displaying.

df = filter_df.toPandas()
    
df2 = df[['date', 'num_changed', '7_day_avg']]
df2['date'] = pd.to_datetime(df2.date).dt.date
df2 = df2.sort_values('date')
plt.figure(figsize=(12.33, 6.5))
ax = sns.barplot(data=df2, x='date', y='num_changed', color='lightgrey')
ax.set_title('Chart title', pad=10)
ax.grid(linestyle='--', axis='y')
ax.spines['right'].set_visible(True)
ax.set_xticklabels(df2.date, rotation=45)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=2))
ax.yaxis.set_label_position("left")
ax.yaxis.tick_left()
ax.set_ylabel('Total 7 Day Change')
ax.set_xlabel('')
ax2 = ax.twinx()  # instantiate a second axes that shares the same x-axis
ax2 = sns.lineplot(data=df2, x='date', y='7_day_avg')
ax2.yaxis.set_label_position("right")
ax2.yaxis.tick_right()
ax2.set_ylim(bottom=0)
ax2.set_ylabel('Avg Conc')
ax2.spines['top'].set_visible(False)

plt.show()

Resulting chart

A sample of the data is: enter image description here

  • 1
    Does this answer your question? [Seaborn boxplot and lineplot not showing properly](https://stackoverflow.com/questions/65423023/seaborn-boxplot-and-lineplot-not-showing-properly) The problem has nothing to do with twin axes - you are trying to combine the categorical barplot with a numerical lineplot. Please note also that your barplot is evenly spaced - it does not reflect the date time properly. – Mr. T Feb 19 '21 at 12:43

2 Answers2

1

This issue can also occur when using the pandas groupby function.

I was trying to plot water level data and rainfall data on two different y axis. Originally when each .csv was imported, the dates were converted to datetime format. However, as my office mate pointed out after much frustration, the pandas .groupby function resets the datetime to an object. To fix the issue I had to re-specify the data format in my groupby loop.

starball
  • 20,030
  • 7
  • 43
  • 238
Andrew
  • 11
  • 1
0

This turns out to be an issue of mixing seaborn charts with matplotlib formatting. Once I removed the seaborn chart calls and used ax.bar() and ax2.plot(), the issue was resolved.