2017-01-16 231 views
2

我生成了一些数据并尝试在同一图表中将它们可视化为两个图形。一个是酒吧,另一个是一条线。具有相同数据的Matplotlib图形不重叠

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

这里是我的代码:

# 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) 

这里是图。

enter image description here

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

+0

这个问题是,我想,在乔金顿的回答[这里]编辑描述(http://stackoverflow.com/questions/7733693/matplotlib-overlay-plot S-与-不同尺度)。但是,现在已经有5年的历史,并且由于我怀疑这是可取的行为,我不知道是否有一个很好的解决方案。还在寻找。 – roganjosh

回答

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() 
1

这是因为序列图使用指标,设置use_indexFalse将解决这个问题,我也建议使用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() 

结果显示低于 plot

相关问题