python - 如何从数据框制作 3D 条形图

标签 python matplotlib 3d bar-chart

这是我的 df 的样子:

hr    slope  value   
8      s_1     6     
10     s_1     2     
8      s_2     4     
10     s_2     8    
我想制作一个 3D 条形图,x 轴为 'hr',y 轴为 'value',z 轴为 'slopes'。
xpos = df['hr']
ypos = df['value']
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos=np.zeros(df.shape).flatten()

dx=0.5 * np.ones_like(zpos)
dy=0.5 * np.ones_like(zpos)
dz=df.values.ravel()

ax.bar3d(xpos,ypos,zpos,dx,dy,dz,color='b', alpha=0.5)
plt.show()
我收到以下错误消息:
ValueError: shape mismatch: objects cannot be broadcast to a single shape
非常欢迎任何帮助,
先感谢您

最佳答案

bar3d() 的文档可以在 https://matplotlib.org/mpl_toolkits/mplot3d/api.html#mpl_toolkits.mplot3d.axes3d.Axes3D.bar3d 找到。 Here 是对它的解释。官方演示可以在 https://matplotlib.org/3.1.1/gallery/mplot3d/3d_bars.html 找到。

import matplotlib.pyplot as plt

xpos = [1, 2, 3]  # x coordinates of each bar
ypos = [0, 0, 0]  # y coordinates of each bar
zpos = [0, 0, 0]  # z coordinates of each bar
dx = [0.5, 0.5, 0.5]  # Width of each bar
dy = [0.5, 0.5, 0.5]  # Depth of each bar
dz = [5, 4, 7]        # Height of each bar

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.bar3d(xpos,ypos,zpos,dx,dy,dz, color='b', alpha=0.5)

plt.show()
enter image description here
出现此错误的问题是 xpos, ypos, zpos, dx, dy, dz 的长度不一样。此外,dz 的元素包含字符串。
这是我如何重现您的示例
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.read_csv('1.csv')

xpos = df['hr']
ypos = df['value']

xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()

zpos = np.zeros(df.shape).flatten()

dx = 0.5 * np.ones_like(zpos)
dy = 0.5 * np.ones_like(zpos)
dz = df[['hr', 'value']].values.ravel()

print(xpos)
print(ypos)
print(zpos)
print(dx)
print(dy)
print(dz) # [8 's_1' 6 10 's_1' 2 8 's_2' 4 10 's_2' 8]

print(len(xpos))  # 16
print(len(ypos))  # 16
print(len(zpos))  # 12
print(len(dx))    # 12
print(len(dy))    # 12
print(len(dz))    # 12

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.bar3d(xpos,ypos,zpos,dx,dy,dz,color='b', alpha=0.5)

plt.show()
1.csv 的内容是
hr,slope,value
8,s_1,6
10,s_1,2
8,s_2,4
10,s_2,8

关于python - 如何从数据框制作 3D 条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63015639/

相关文章:

c# - 3D 中两个矩形之间的交集

python - 将 xyz + var pandas 数据框转换为 numpy 3d 网格

python - 获取图像模式 PIL Python

python - 使用 matplotlib 导出动画 gif

javascript - mpld3:如何使用插件更改工具栏的位置?

python - 如何在 Jupyter 中从 PILLOW 导入图像?

3D线平面相交,与简单平面

python - 从文件名中提取单词列表

Python:使用 FFTW 加载 DLL 时找不到模块(OSError:[WinError 126])

Python - 在多处理调用之前修改的全局变量作为原始状态传递