【问题标题】:How to produce 3D segmented bar plot with R如何使用 R 生成 3D 分段条形图
【发布时间】:2021-03-25 07:06:26
【问题描述】:

我们如何使用 R 生成 3D 'segmented' 条形图?我找到了一个类似的post,但它在多年前就关闭了,直到现在还没有给出有效的答案。我可以使用python 找到解决方案,但我真的想用 R 生成它。

我知道后面的一些条形图不会清晰呈现,但我不担心。尽管在 3D 中正确呈现数据存在问题,但我仍然希望生成它,如果可能的话,旋转以便可以从不同的角度观察后面的人。

有人可以帮忙吗?谢谢。

【问题讨论】:

标签: r 3d bar-chart


【解决方案1】:

由于我无法获得使用 R 的答案,我尝试使用 python(其他 post 的解决方案,但堆栈数量增加)并实现了我想要的,我可以在其中旋转并查看条形图不同的角度。

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


# Set plotting style
plt.style.use('seaborn-white')

dz=[]
z0 = np.array([ 1.,  3.,  11.,   8.,   7.,   6.,   6.,   6.,   5.,   4.,
                3.,   11.,   10.,  1.,  1.,  7.])
dz.append(z0)

z1 =[ 5.,   5.,   8.,   4.,   2.,   0.,   0.,   0.,   0.,   0.,   0.,
      1.,   6.,  5.,   7.,   2.]

dz.append(z1)

z2 =[ 15.,   5.,   8.,   2.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
      3.,   5.,  2.,   7.,   2.]

dz.append(z2)

_zpos = z0*0


xlabels = pd.Index(['X01', 'X02', 'X03', 'X04'], dtype='object')

ylabels = pd.Index(['Y01', 'Y02', 'Y03', 'Y04'], dtype='object')

x = np.arange(xlabels.shape[0])

y = np.arange(ylabels.shape[0])

x_M, y_M = np.meshgrid(x, y, copy=False)

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

# Making the intervals in the axes match with their respective entries
ax.w_xaxis.set_ticks(x + 0.5/2.)
ax.w_yaxis.set_ticks(y + 0.5/2.)

# Renaming the ticks as they were before
ax.w_xaxis.set_ticklabels(xlabels)
ax.w_yaxis.set_ticklabels(ylabels)

# Labeling the 3 dimensions
ax.set_xlabel('X label')
ax.set_ylabel('Y label')
ax.set_zlabel('Z label')

# Choosing the range of values to be extended in the set colormap
values = np.linspace(0.2, 1., x_M.ravel().shape[0])

# Selecting an appropriate colormap

colors = ['#FFC04C', 'blue', '#3e9a19', 
          '#599be5','#bf666f','#a235bf','#848381','#fb90d6','#fb9125']

# Increase the number of segment to 3 by changing the X in 'range(X)' to 3.
for i in range(3):
    ax.bar3d(x_M.ravel(), y_M.ravel(), _zpos, dx=0.3, dy=0.3, dz=dz[i], 
              color=colors[i])
    _zpos += dz[i]
 

#plt.gca().invert_xaxis()
#plt.gca().invert_yaxis()
Segment1_proxy          = plt.Rectangle((0, 0), 1, 1, fc="#FFC04C90")   
Segment2_proxy         = plt.Rectangle((0, 0), 1, 1, fc="blue")

ax.legend([Segment1_proxy,
           Segment2_proxy],['Segment1',
                            'Segment2',
         ])
plt.show()

【讨论】:

    猜你喜欢
    • 2023-01-08
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多