【问题标题】:How can I use a nested dict keys as categorical variables to plot them using matplotlib?如何使用嵌套的 dict 键作为分类变量来使用 matplotlib 绘制它们?
【发布时间】:2019-04-28 08:40:51
【问题描述】:

我习惯于在 R 中使用 ggplot 绘制东西,而我正在努力使用 matplotlib 在 Python 中可视化存储在嵌套 dicts 中的时间序列数据。特别是,我想根据字典的“键”作为分类变量来更改颜色和其他绘图属性。

这是一个非常简单的例子,它看起来像我的嵌套字典:

mydict = {'subdict1': {'test_1': {'trial_1': np.array([[np.arange(0.0, 1.0, 0.01)],
                                                     [np.sin(2*np.pi*np.arange(0.0, 1.0, 0.01))]]),
                                  'trial_2': np.array([[np.arange(0.0, 1.0, 0.01)],
                                                     [np.sin(3*np.pi*np.arange(0.0, 1.0, 0.01))]])},


                      'test_2': {'trial_1': np.array([[np.arange(0.0, 1.0, 0.01)],
                                                     [np.sin(4*np.pi*np.arange(0.0, 1.0, 0.01))]]),
                                 'trial_2': np.array([[np.arange(0.0, 1.0, 0.01)],
                                                       [np.sin(5*np.pi*np.arange(0.0, 1.0, 0.01))]])}}}

我想轻松绘制数组图,但使用 test_n 键 dict 来着色或塑造线条。以下代码绘制了示例数组,但 for 循环中的每次迭代使用不同的颜色:

fig, ax = plt.subplots(1)
for x in mydict.keys():
    for y in mydict[x].keys():
        for z in mydict[x][y].keys():
            ax.plot(mydict[x][y][z][0][0], mydict[x][y][z][1][0])

我知道other possibilities 使用seaborn 或pandas。但是,我的嵌套 dicts 很复杂并且包含许多不同的数组,所以我不确定将所有数据存储为 data_frame 格式是否是个好主意?

或者(尽管这可能是一个不同的问题?),我想知道将我的嵌套字典转换为 R 对象的推荐方法是什么,以便利用R's ggplot 的分类映射功能。

【问题讨论】:

  • 问题是什么,因为您显示的代码显然给了您正确的结果?我错过了什么吗?
  • 我希望情节由test_1test_2 键着色(即只有两种颜色)。它目前为每条绘制的线提供不同的颜色。

标签: python r matplotlib ggplot2


【解决方案1】:

也许您想将所有z 的颜色设置为相同?

fig, ax = plt.subplots(1)
colors = iter(plt.rcParams["axes.prop_cycle"].by_key()['color'])

for x in mydict.keys():
    for y in mydict[x].keys():
        c = next(colors)
        for z in mydict[x][y].keys():
            ax.plot(mydict[x][y][z][0][0], mydict[x][y][z][1][0], color=c, label=z)

ax.legend()      
plt.show()

【讨论】:

  • 谢谢,这就是我要找的。如何正确使用legend() 提供z 标签?
  • 你的意思是你在图例中看到每个标签两次,因为你有两个相同标签的曲线?
  • 是的,我不知道如何使用legend() 提供准确的颜色和z 键?
  • 我更新了答案,但我不清楚你想在图例中显示什么。
猜你喜欢
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多