将Pandas数据框绘制成三维条形图

2024-05-04 04:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题有一个现有的答案here,但它是错误的

在上一个问题的示例数据框中,美国拥有最多的python用户(10110),但在图中,似乎法国拥有最多的python用户

有人能帮我修复解决方案代码吗

Data Frame

Resulting Graph (incorrect)

数据帧示例:

EG 

Language    C     C++     Java    Python    Perl

Country

USA          3222   343     2112   10110      89

France      5432   323     1019     678        789

Japan       7878   467       767     8788       40

错误代码:

from mpl_toolkits.mplot3d import Axes3D

# thickness of the bars
dx, dy = .8, .8

# prepare 3d axes
fig = plt.figure(figsize=(10,6))
ax = Axes3D(fig)

# set up positions for the bars 
xpos=np.arange(eg.shape[0])
ypos=np.arange(eg.shape[1])

# set the ticks in the middle of the bars
ax.set_xticks(xpos + dx/2)
ax.set_yticks(ypos + dy/2)

# create meshgrid 
# print xpos before and after this block if not clear
xpos, ypos = np.meshgrid(xpos, ypos)
xpos = xpos.flatten()
ypos = ypos.flatten()

# the bars starts from 0 attitude
zpos=np.zeros(eg.shape).flatten()

# the bars' heights
dz = eg.values.ravel()

# plot 
ax.bar3d(xpos,ypos,zpos,dx,dy,dz)

# put the column / index labels
ax.w_yaxis.set_ticklabels(eg.columns)
ax.w_xaxis.set_ticklabels(eg.index)

# name the axes
ax.set_xlabel('Country')
ax.set_ylabel('Language')
ax.set_zlabel('Count')

plt.show()

Tags: the数据用户示例npaxegshape
1条回答
网友
1楼 · 发布于 2024-05-04 04:35:12

要解决这个问题,只需更改代码的ravel部分:

# the bars' heights
dz = eg.values.ravel(order='F')

确保order='F'reads为您的问题正确输入数据:

‘F’ means to index the elements in column-major, Fortran-style order, with the first index changing fastest, and the last index changing slowest.

您提供的代码无法按预期工作,因为xposypos位置数组未按通过eg.values.ravel()获得的dz数组排序:

eg.values.ravel()
>> array([ 3222,   343,  2112, 10110,    89,  5432,   323,  1019,   678,
         789,  7878,   467,   767,  8788,    40], dtype=int64)

此数组(图表的“高度”)连接eg行的值。换句话说,dz按以下顺序获取eg术语:

(0,0)、(0,1)、(0,2)、(0,3)、(1,0)

但是xposypos是沿着列列出的值:

list(zip(xpos, ypos))
>>[(0, 0),(1, 0),(2, 0),(0, 1),(1, 1),(2, 1),(0, 2),...]

因此,您的值分配不正确。例如,(1,0)-即,法国,C -接收来自(0,1)-美国,C++的值。这就是为什么图表上的值被弄乱了

希望有帮助

相关问题 更多 >