[英]How to align the x position of the dots in seaborn scatterplot to a nested bar plot
我正在嘗試使用sns.scatterplot()
和df.plot(kind='bar')
在條形 plot 結果證明這個數字很好,但如果我可以將每個散點與具有相同 label 的相應條對齊,那就更好了。
我已經閱讀了關於matplotlib.pyplot
矩形的文檔,它有一個get_x()
方法可以“返回矩形的左坐標”;
我想知道是否有辦法將這些坐標分配給 seaborn 繪制的散點?
fig, ax = plt.subplots(nrows=1, ncols=1)
fig.set_size_inches(9, 9)
fig.set_dpi(300)
bar_df.plot(kind='bar', ax=ax)
ax2 = ax.twinx()
sns.scatterplot(data=line_df, ax=ax2)
年 | 蘋果 | 香蕉 | 柑橘 | ... |
---|---|---|---|---|
2020 | 12 | 34 | 56 | 78 |
2025 | 12 | 34 | 56 | 78 |
2030 | 12 | 34 | 56 | 78 |
2035 | 12 | 34 | 56 | 78 |
年 | 蘋果 | 香蕉 | 柑橘 | ... |
---|---|---|---|---|
2020 | 23 | 45 | 67 | 89 |
2025 | 23 | 45 | 67 | 89 |
2030 | 23 | 45 | 67 | 89 |
2035 | 23 | 45 | 67 | 89 |
如果我可以用相同的 header 將點放在與條相同的垂直線上,那就太好了;
sns.scatterplot
將 x 軸解釋為數字。 因此,它不能很好地與條形 plot 對齊,也沒有dodge=
參數。 您可以改用sns.stripplot
。
Seaborn 最容易使用“長格式”的數據,這可以通過 pandas pd.melt
來實現。
這是一些示例代碼:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
bar_df, line_df = pd.read_html('https://stackoverflow.com/questions/73191315')
bar_df_long = bar_df.melt(id_vars='year', var_name='fruit', value_name='bar_value')
line_df_long = line_df.melt(id_vars='year', var_name='fruit', value_name='line_value')
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6,6), dpi=300)
sns.barplot(data=bar_df_long, x='year', y='bar_value', hue='fruit', dodge=True, ax=ax)
ax2 = ax.twinx()
sns.stripplot(data=line_df_long, x='year', y='line_value', hue='fruit', dodge=True, jitter=False,
edgecolor='black', linewidth=1, ax=ax2)
ax2.legend_.remove() # remove the second legend
plt.tight_layout()
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.