用 pandas 绘制多索引数据 [英] Plotting multi indexed data with pandas
问题描述
我有一个 Python 字典,格式如下:
I have a Python dictionary in the form of:
dict = {0: {a: 1, b: 2}, 1: {a: 1, b: 2}}
我使用 from_dict()
从中创建了一个 Pandas DataFrame
.正如预期的那样,这给了我一个多索引数据帧.
I created a Pandas DataFrame
from it, by using from_dict()
. This gave me a multiindex dataframe`, as expected.
现在我想绘制这个数据框,外部索引是 x 轴,内部索引是我的图表中的单独线,y 轴上的数据点是值.
Now I want to plot this dataframe with the outer index being the x-axis and the inner index being separate lines in my graph, the data points on the y-axis being the values.
我尝试将它们堆叠起来,但它只给了我一行.
I tried stacking them, but it only gave me a single line.
我当前的代码:
data = pd.DataFrame.from_dict(my_data)
data = data.T.stack()
data.plot()
有人知道如何做到这一点吗?
Anyone has an idea how this could be done?
推荐答案
使用
data.groupby(level=1).plot(stacked=True)
<小时>
import pandas as pd
import matplotlib.pyplot as plt
my_data = {0: {'a': 1, 'b': 2}, 1: {'a': 1, 'b': 2}}
data = pd.DataFrame.from_dict(my_data)
data = data.T.stack()
# 0 a 1
# b 2
# 1 a 1
# b 2
# dtype: int64
data.groupby(level=1).plot(stacked=True, legend=True)
plt.show()
<小时>
或者,为了更好地控制配置绘图,直接使用 matplotlib 可能更容易:
Or, for more control in configuring the plot it may be easier to use matplotlib directly:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.concat({key:pd.Series(np.random.randint(10, size=(10,))) for key in 'AB'}).swaplevel()
fix, ax = plt.subplots()
for key, grp in data.groupby(level=1):
ax.plot(grp.index.get_level_values(0), grp.values, label=key)
plt.legend()
plt.plot()
plt.show()
这篇关于用 pandas 绘制多索引数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!