Skip to main content
 首页 » 编程设计

python之如何用 pandas 和 matplotlib 绘制两个分类(名义)系列之间的比较

2025年05月04日12duanxz

我正在尝试比较一系列元素的两种不同分类。假设我想获得这样的图形:

通过以下 iPython session 获得:

In [1]: df 
Out[1]:  
<class 'pandas.core.frame.DataFrame'> 
Index: 446 entries, element0 to element445 
Data columns (total 2 columns): 
Classification1       446  non-null values 
Classification2    446  non-null values 
dtypes: int64(2) 
 
In [2]: pylab.pcolor(df, cmap='Oranges') 
Out[2]: <matplotlib.collections.PolyCollection at 0x55dc650> 
 
In [3]: pl.show() 

1)如何查看两个分类中相同的值是否使用相同的颜色? IE。我如何测试在两个分类中具有相同颜色的 element1 是否也具有相同的值(例如,在 Classification1 和 Classification2 中都被分类为 1)? 我尝试使用 pl.legend() 但它告诉我:

In [54]: pl.legend() 
/usr/lib/pymodules/python2.7/matplotlib/axes.py:4486: UserWarning: No labeled objects found. Use label='...' kwarg on individual plots. 
  warnings.warn("No labeled objects found. " 

2) 是否有更好的方法以图形方式比较这两个分类?

谢谢

请您参考如下方法:

我觉得这个比你之前的回答更符合你的要求

levels = [0.0, 1.0, 2.0] 
a = np.random.choice(levels, size=10) 
a_array = np.vstack((a, a)).T 
 
b = np.random.choice(levels, size=10) 
b_array = np.vstack((b, b)).T 
 
ax = plt.subplot(121) 
CS = ax.contourf(a_array, 2, level=levels, colors=('r', 'g', 'b')) 
 
ax = plt.subplot(122) 
CS = ax.contourf(b_array, 2, level=levels, colors=('r', 'g', 'b')) 
 
Cbar = plt.colorbar(CS) 
 
Cbar.set_ticks(levels) 
Cbar.set_ticklabels(["series 1", "series 2", "series 3"]) 

据我所知,pcolor 无法以这种方式设置标签。尽管如果可以的话,q 会是一个更好的方法