【问题标题】:Matplotlib graph with same data doesn't overlap具有相同数据的 Matplotlib 图不重叠
【发布时间】:2017-01-16 11:16:46
【问题描述】:

我已经生成了一些数据,并尝试将它们可视化为同一个图中的两个图表。一根为条,一根为线。

但由于某种原因,这些图表似乎没有重叠。

这是我的代码:

# roll two 6-sided dices 500 times
dice_1 = pd.Series(np.random.randint(1, 7, 500))
dice_2 = pd.Series(np.random.randint(1, 7, 500))

dices = dice_1 + dice_2

# plotting the requency of a 2 times 6 sided dice role
fc = collections.Counter(dices)
freq = pd.Series(fc)
freq.plot(kind='line', alpha=0.6, linestyle='-', marker='o')
freq.plot(kind='bar', color='k', alpha=0.6)

这是图表。

数据集是相同的,但是折线图向右移动了两个数据点(从 4 开始而不是 2)。如果我分别绘制它们,它们会正确显示(都从 2 开始)。那么如果我将它们绘制在同一张图中有什么不同呢?以及如何解决这个问题?

【问题讨论】:

  • 我认为,这个问题在 Joe Kington 的回答 here 的编辑中有所描述。但是,现在已经 5 岁了,由于我怀疑这是可取的行为,我想知道是否有一个很好的解决方案。还在寻找。

标签: python matplotlib


【解决方案1】:

我找不到比重新提供 x 轴数据更简单的方法。如果这代表了您正在使用的更大的方法,那么您可能需要从pd.Series() 绘制这些数据,而不是使用列表,但这段代码至少会为您提供您想要的图。如果您使用的是 Python 3,请将 iteritems() 更改为 items()

似乎在折线图之后发生了一些 x 轴的自动缩放,这使两个图不同步了两个点(可能的最低值)。在绘制两个图之前,可能会在 x 轴上禁用此自动缩放,但这似乎更困难。

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

# roll two 6-sided dices 500 times
dice_1 = pd.Series(np.random.randint(1, 7, 500))
dice_2 = pd.Series(np.random.randint(1, 7, 500))

dices = dice_1 + dice_2

# plotting the requency of a 2 times 6 sided dice role
fc = collections.Counter(dices)

x_axis = [key for key, value in fc.iteritems()]
y_axis = [value for key, value in fc.iteritems()]

plt.plot(x_axis, y_axis, alpha=0.6, linestyle='-', marker='o')
plt.bar(x_axis, y_axis, color='k', alpha=0.6, align='center')
plt.show()

【讨论】:

    【解决方案2】:

    发生这种情况是因为系列情节使用索引,将use_index 设置为False 将解决此问题,我还建议使用groupbylen 来计算每个组合的频率

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    # roll two 6-sided dices 500 times
    dice_1 = pd.Series(np.random.randint(1, 7, 500))
    dice_2 = pd.Series(np.random.randint(1, 7, 500))
    dices = dice_1 + dice_2
    
    # returns the corresponding value of each index from dices
    func = lambda x: dices.loc[x]
    
    fc = dices.groupby(func).agg({'count': len})
    
    ax = fc.plot(kind='line', alpha=0.6, linestyle='-',
                 marker='o', use_index=False)
    fc.plot(ax=ax, kind='bar', alpha=0.6, color='k')
    
    plt.show()
    

    结果如下图

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-18
      • 2021-11-27
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      相关资源
      最近更新 更多