Skip to main content
 首页 » 编程设计

python之具有相同数据的 Matplotlib 图不重叠

2024年10月17日8duanxz

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

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

这是我的代码:

# 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 开始)。那么,如果我将它们绘制在同一张图中,会有什么不同呢?以及如何解决这个问题?

请您参考如下方法:

我找不到比重新提供 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()