[英]Barplot with twinx and two bars per month
一个给定的df,其中索引是月份,两列'Ta'和'G_Bn'。
这些列应使用 seaborn 针对月份绘制,以获得具有两个 y 轴的条形图。 一个用于“Ta”,一个用于“G_Bn”。 酒吧必须彼此相邻。 我的想法:
#Create combo chart
fig, ax1 = plt.subplots(figsize=(20,10))
ax1 = sns.barplot(data=dataMonthly, color ='#2b83ba')
ax1.tick_params(axis='y')
ax1.set_xlabel('Time')
ax1.set_ylabel('Value1')
ax2 = ax1.twinx()
ax2 = sns.barplot(x = dataMonthly.index, y = "Ta", data=dataMonthly, color ="#404040")
ax2.set_ylabel('Value2')
ax2.tick_params(axis='y')
plt.show()
问题是这些条总是相互重叠,因为我在 ax1 上是 plot,然后是 ax2。 我该如何解决? 有任何想法吗?
以下方法创建一个虚拟分类变量作为hue
:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
dataMonthly = pd.DataFrame({'G_Bn': np.random.uniform(30, 40, 5).cumsum(),
'Ta': np.random.uniform(5, 10, 5).cumsum()})
fig, ax1 = plt.subplots(figsize=(20, 10))
ax2 = ax1.twinx()
palette = ['#2b83ba', "#404040"]
categories = ["G_Bn", "Ta"]
for ax, cat_val in zip([ax1, ax2], categories):
sns.barplot(x=dataMonthly.index, y=dataMonthly[cat_val],
hue=pd.Categorical([cat_val] * len(dataMonthly), categories), palette=palette, ax=ax)
ax1.set_xlabel('Time')
ax2.legend_.remove() # a legend was created for ax1 as well as ax2
plt.tight_layout()
plt.show()
PS:注意如果在调用seaborn function之前创建了ax
,强烈建议使用ax=...
参数,不要抓到seaborn的ZC1C425268E68384F1AB4ZA79的返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.