[英]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.