【问题标题】:X Axis date range changing when using twinx()使用 twinx() 时 X 轴日期范围发生变化
【发布时间】:2021-02-20 00:28:39
【问题描述】:

当我绘制图表时,条形图的日期更改为 1970 年代,而叠加的线图保持正确。如果我从 twinx() 开始删除代码,则条形图会在正确的日期范围内正确显示。我也尝试从线图中删除 x 参数,但它只会导致线图不显示。

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()

数据样本是:

【问题讨论】:

  • 这能回答你的问题吗? Seaborn boxplot and lineplot not showing properly 这个问题与双轴无关 - 您正在尝试将分类条形图与数值线图结合起来。另请注意,您的条形图是均匀分布的 - 它不能正确反映日期时间。

标签: python pandas matplotlib seaborn twinx


【解决方案1】:

结果证明这是将 seaborn 图表与 matplotlib 格式混合的问题。一旦我删除了 seaborn 图表调用并使用了 ax.bar() 和 ax2.plot(),问题就解决了。

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2013-08-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多