熊猫数据帧以3D形式绘制多个帧

时间:2020-09-23 10:12:59

标签: pandas matplotlib

我想在一张3D图形中绘制两个数据框

data1 = {'numbers': [1,2,3,4,5,6,7,8,9,10], 'frequency': [5,2,1,6,9,3,8,2,0,5]} 
data2 = {'numbers': [1,2,3,4,5,6,7,8,9,10], 'frequency': [19,12,1,26,19,33,28,28,10,5]} 
newdf = pd.DataFrame(data1)
newdf2= pd.DataFrame(data2)
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(111, projection='3d')
newdf.plot(kind='bar',x ='numbers', y='frequency',figsize=(10,5), color='thistle', width=.4, legend=True, alpha=0.8, ax=ax)
newdf2.plot(kind='bar',x ='numbers', y='frequency',figsize=(10,5), color='navy', width=.2,legend=True, alpha=1,ax=ax) 
plot.show()

这将两个图形都绘制在一个图形中,但是y和z轴已转置。我想在z平面上绘制每个数据集,并用数字表示x轴,频率表示y轴。我不从所有示例中了解如何实现这一目标。我也想将条形图绘制为3d条形图。我很感谢您的帮助

2 个答案:

答案 0 :(得分:1)

我只是在猜测,因为我没有想要看到的输出类型的示例,但是您想要实现以下示例的3D图形是:y轴是数据帧的类型和z轴是频率。

import matplotlib.pyplot as plt

data1 = {'numbers': [1,2,3,4,5,6,7,8,9,10], 'frequency': [5,2,1,6,9,3,8,2,0,5]} 
data2 = {'numbers': [1,2,3,4,5,6,7,8,9,10], 'frequency': [19,12,1,26,19,33,28,28,10,5]} 
newdf = pd.DataFrame(data1)
newdf2 = pd.DataFrame(data2)

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

yticks = [4,3,2,1,0]
ax.bar(newdf['numbers'], newdf['frequency'], zs=3, zdir='y', color='b', alpha=0.8)
ax.bar(newdf2['numbers'], newdf2['frequency'], zs=1, zdir='y', color='r', alpha=0.8)

ax.set_xlabel('number')
ax.set_ylabel('df_type')
ax.set_zlabel('frequency')

ax.set_yticks(yticks)

plt.show()

enter image description here

bar3d类型

# ax.bar3d(xpos, ypos, zpos, dx, dy, dz)
ax.bar3d(newdf['numbers'], 3, 0, dx=1, dy=1, dz=newdf['frequency'], color='b', alpha=0.6)
ax.bar3d(newdf2['numbers'], 0, 0, dx=1, dy=1, dz=newdf2['frequency'], color='r', alpha=0.3)

enter image description here

答案 1 :(得分:0)

这是我手头上的一种解决方案(找不到原始链接)。

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd

# datasets
data1 = {'numbers': [1,2,3,4,5,6,7,8,9,10], 'frequency': [5,2,1,6,9,3,8,2,0,5]} 
data2 = {'numbers': [1,2,3,4,5,6,7,8,9,10], 'frequency': [19,12,1,26,19,33,28,28,10,5]} 

newdf = pd.DataFrame(data1)
newdf2= pd.DataFrame(data2)

# put all the data in one place
# can use data1['frequency'] and data2['frequency'] directly
data = np.array([
        newdf['frequency'].values,
        newdf2['frequency'].values,
        ])

fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111, projection='3d')
colors = ["r","g","b"]*5  # for up to 15 sets of bars

# Draw 3D bars 
ncnt, nbins = data.shape[:2]
xs = np.arange(nbins)
for i in range(ncnt):
    ys = data[i]
    cs = [colors[i]] * nbins
    ax.bar(xs, ys.ravel(), zs=i, zdir='x', color=cs, alpha=0.8)

ax.set_xlabel('data_frame')
ax.set_ylabel('numbers')
ax.set_zlabel('frequency')

ax.set_xticks(range(data.shape[0]))    # 2 dataframes
ax.set_yticks(newdf['numbers'].values) # from 'numbers' column

plt.show()

输出图:

output-plot