【发布时间】:2022-03-14 22:11:37
【问题描述】:
我无法使用我将在下面显示的“结果”数据框的数据(使用“a”数据、“b”数据和“百分位数') 在 Python 中。
当我单独绘制它们时,我可以很好地绘制线图(使用“a”数据),但是,我试图绘制的条形图的 x 轴值(使用“b”数据)不显示向上。奇怪的是,我可以使用我试图用('b'数据)绘制条形图的相同数据绘制线图而没有任何问题
当我尝试将它们绘制在同一个图上时,x 轴从“结果”数据框中甚至不存在的日期开始。
我什至尝试将结果数据框导出为 csv 并重新导入以查看是否可行,但我遇到了同样的问题。
我想要达到的目标:
- 将“a”数据绘制为线图,将“b”数据绘制为具有不同 y 轴的同一 seaborn 图上的条形图
- 我想要相同数量的 y 轴代码,并让两个 y 轴的 0 对齐
- 最后,我希望条形图的颜色取决于百分位列是否指示“低”、“中”、“高”(每种颜色不同)
# Here is the 'a' and 'b' data that I start with
a = pd.read_csv(r'a.csv',sep=",", parse_dates=['date'], dayfirst=True, index_col=0)
b = pd.read_csv(r'b.csv',sep=",", parse_dates=['date'], dayfirst=True, index_col=0)
# After manipulating the data, here is the 'results' DataFrame I end up with
# Plotting them separately
# Plotting lineplot using 'a' column from 'results' DataFrame
sns.lineplot(data=result.iloc[:, 0], color="g")
# Plotting barplot using 'b' column from 'results' DataFrame
b_plot = sns.barplot(data=result, x=result.index, y=result.iloc[:, 2], color="b")
b_plot.xaxis.set_major_locator(md.YearLocator(base=4))
b_plot.xaxis.set_major_formatter(md.DateFormatter('%Y'))
b_plot.margins(x=0)
# Attempting to plot the lineplot and barplot on the same plot
matplotlib.rc_file_defaults()
ax1 = sns.set_style(style=None, rc=None)
fig, ax1 = plt.subplots(figsize=(12,6))
a_plot = sns.lineplot(data=result.iloc[:, 0], color="g", ax=ax1)
ax2 = ax1.twinx()
b_plot = sns.barplot(data=result, x=result.index, y=result.iloc[:, 2], color="b", ax=ax2)
b_plot.xaxis.set_major_locator(md.YearLocator(base=4))
b_plot.xaxis.set_major_formatter(md.DateFormatter('%Y'))
b_plot.margins(x=0)
lineplot and barplot on same plot
编辑:我已经回答了以下问题
【问题讨论】:
-
在为每个绘图调用 seaborn 绘图命令之前尝试调用
f, ax = plt.subplots() -
欢迎来到 SO。请阅读How do I ask a good question? 和How to create a minimal, complete, and reproducible example。你应该避免问几个不同的问题。
-
@Mr. T 我已经尝试了您链接的页面上的解决方案。但是,当我在同一个图上绘制两者时,我的 x 轴日期时间索引仍然不显示。当我单独做线图时没有问题。但是,即使我单独进行 seaborn barplot,x 轴上的日期时间索引也不会显示
标签: python pandas plot seaborn