[英]Seaborn boxplot with 2 y-axes
如何創建一個帶有2個y軸的seaborn boxplot? 因為尺度不同,我需要這個。 我當前的代碼將覆蓋boxplot中的第一個框,例如。 它由第一個ax的第一個數據項和第二個ax的第一個項填充。
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
df = pd.DataFrame({'A': pd.Series(np.random.uniform(0,1,size=10)),
'B': pd.Series(np.random.uniform(10,20,size=10)),
'C': pd.Series(np.random.uniform(10,20,size=10))})
fig = plt.figure()
# 2/3 of A4
fig.set_size_inches(7.8, 5.51)
plt.ylim(0.0, 1.1)
ax1 = fig.add_subplot(111)
ax1 = sns.boxplot(ax=ax1, data=df[['A']])
ax2 = ax1.twinx()
boxplot = sns.boxplot(ax=ax2, data=df[['B','C']])
fig = boxplot.get_figure()
fig
如何防止第一項被覆蓋?
編輯:
如果我添加職位論證
boxplot = sns.boxplot(ax=ax2, data=df[['B','C']], positions=[2,3])
我得到一個例外:
TypeError: boxplot() got multiple values for keyword argument 'positions'
可能是因為seaborn已經在內部設定了這個論點。
在這里使用seaborn可能沒有多大意義。 使用通常的matplotlib boxplots允許您按預期使用positions
參數。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
df = pd.DataFrame({'A': pd.Series(np.random.uniform(0,1,size=10)),
'B': pd.Series(np.random.uniform(10,20,size=10)),
'C': pd.Series(np.random.uniform(10,20,size=10))})
fig, ax1 = plt.subplots(figsize=(7.8, 5.51))
props = dict(widths=0.7,patch_artist=True, medianprops=dict(color="gold"))
box1=ax1.boxplot(df['A'].values, positions=[0], **props)
ax2 = ax1.twinx()
box2=ax2.boxplot(df[['B','C']].values,positions=[1,2], **props)
ax1.set_xlim(-0.5,2.5)
ax1.set_xticks(range(len(df.columns)))
ax1.set_xticklabels(df.columns)
for b in box1["boxes"]+box2["boxes"]:
b.set_facecolor(next(ax1._get_lines.prop_cycler)["color"])
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.