简体   繁体   English

如何在不破坏标准化的情况下在图中堆叠数据

[英]How to stack data in plot without breaking normalization

I need to work with huge csv files looking something like this我需要处理看起来像这样的巨大 csv 文件

x       y1      y2      y3      y4      y5      y6      y7      y8      y9
5.01    0.11    0.12    0.12    0.12    0.12    0.12    0.11    0.12    0.11
5.04    0.11    0.12    0.12    0.12    0.12    0.12    0.11    0.11    0.11
5.07    0.11    0.12    0.11    0.12    0.12    0.12    0.11    0.12    0.11
5.09    0.11    0.12    0.12    0.12    0.12    0.12    0.11    0.11    0.10
...     ...     ...     ...     ...     ...     ...     ...     ...     ...
47.88   1.00    1.00    1.00    1.00    1.00    1.00    1.00    1.00    1.00
47.90   0.91    0.99    0.88    0.96    0.94    0.98    0.86    0.86    0.85
47.93   0.70    0.81    0.63    0.76    0.73    0.78    0.61    0.61    0.59
47.95   0.46    0.55    0.41    0.51    0.47    0.53    0.40    0.39    0.38

I need to grab the data and plot it and to make it easier to compare.我需要获取数据并绘制它并使其更易于比较。

I've tried to stack them on top of each other我试着把它们叠在一起

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('data.csv', index_col=0)
plt.figure(); df.plot(stacked=True); plt.legend(loc='best')
plt.show()

And I get the following,我得到以下信息,

Stacked data堆叠数据

where the normalization of the data is messed up数据的规范化混乱的地方

I've tried to use the subplot keyword我试过使用 subplot 关键字

plt.figure(); df.plot(subplots=True); plt.legend(loc='best')
plt.show()

In that case, I get this在那种情况下,我得到这个

Plot using subplot keyword使用 subplot 关键字绘图

The sharing of the x-axis is perfect and now I don't have the normalization of the data messed up. x 轴的共享是完美的,现在我没有搞砸数据的标准化。 However, I have these frames and I'm not able to remove them, also I wanted a single legend with all the entries like in the figure above.但是,我有这些框架,我无法删除它们,而且我想要一个包含所有条目的图例,如上图所示。

I prepared four data frames for simple line graphs and used them as data frames.我为简单的折线图准备了四个数据框,并将它们用作数据框。 By using fig, we can get the legend and handle from each axis and add them to the list.通过使用 fig,我们可以从每个轴获取图例和句柄并将它们添加到列表中。 Finally, we set the labels and handles retrieved by fig.legend() .最后,我们设置了fig.legend()检索到的标签和句柄。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

y1 = np.linspace(0,1,50).cumsum()
y2 = np.linspace(0,1,50).cumsum() + 0.01
y3 = np.linspace(0,1,50).cumsum() + 0.02
y4 = np.linspace(0,1,50).cumsum() + 0.03

df = pd.DataFrame({'y1':y1, 'y2':y2, 'y3':y3, 'y4':y4})

fig,ax = plt.subplots()
df.plot(subplots=True, legend=False, ax=ax)

lines = []
labels = []

for ax in fig.axes:
    axLine, axLabel = ax.get_legend_handles_labels()
    lines.extend(axLine)
    labels.extend(axLabel)
    
fig.legend(lines, labels, loc='center', bbox_to_anchor=(1.0,0.5))

plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM