首页 > 解决方案 > Points to Walls Tab 使用 Matplotlib 或 Seaborn 绘制 3D 散点图

问题描述

我想用 将点绘制到 Walls Tab 3D Scatter Plots Matplotlib,如下所示。

在此处输入图像描述

我可以知道,如何修改下面的代码,或者是否有人可以与我分享任何好的资源来实现上述目标

import re, seaborn as sns
import numpy as np

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import ListedColormap

data = {'th': [1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2],
        'pdvalue': [0.5, 0.5, 0.5, 0.5, 0.2,0.2,0.2,0.2,0.3,0.3,0.4,0.1,1,1.1,3,1],
        'my_val': [1.2,3.2,4,5.1,1,2,5.1,1,2,4,1,3,6,6,2,3],
        'name':['a','b','c','d','a','b','c','d','a','b','c','d','a','b','c','d']}
df = pd.DataFrame(data)
# convert unique str into unique int
order_dict = {k: i for i, k in enumerate ( df ['name'])}
df ['name_int'] = df ['name'].map ( order_dict )
data_np=df.to_numpy()

# generate data

x = data_np[:,0]
y = data_np[:,1]
z = data_np[:,2]

# axes instance
fig = plt.figure(figsize=(10,6))
ax = Axes3D(fig)

# get colormap from seaborn
cmap = ListedColormap(sns.color_palette("husl", 256).as_hex())

# plot
sc = ax.scatter(x, y, z, s=40, c=data_np[:,4], marker='o', cmap=cmap, alpha=1)
ax.set_xlabel('th')
ax.set_ylabel('pdvalue')
ax.set_zlabel('my_val')

# legend
plt.legend(*sc.legend_elements(), bbox_to_anchor=(1.05, 1), loc=2)
plt.show()

标签: pythonmatplotlibseaborn

解决方案


扩展JohanC和 @Akroma 提出的建议,这两个建议可以组合如下。

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

# Create an example dataframe
data = {'th': [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2],
'pdvalue': [0.5, 0.5, 0.5, 0.5, 0.2, 0.2, 0.2, 0.2, 0.3, 0.3, 0.4, 0.1, 1, 1.1, 3, 1],
'my_val': [1.2, 3.2, 4, 5.1, 1, 2, 5.1, 1, 2, 4, 1, 3, 6, 6, 2, 3],
'name': ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']}
df = pd.DataFrame ( data )

# axes instance
fig = plt.figure ( figsize=(10, 6) )
ax = Axes3D ( fig, auto_add_to_figure=False )
fig.add_axes ( ax )

# find all the unique labels in the 'name' column
labels = np.unique ( df['name'])
# get palette from seaborn
palette = sns.color_palette ( "husl", len ( labels ) )

# plot
for label, color in zip ( labels, palette ):
    df1 = df[df['name'] == label]
    ax.scatter ( df1['th'], df1['pdvalue'], df1['my_val'],
    s = 40, marker = 'o', color = color, alpha = 1, label = label)

    z2 = np.ones ( shape=df1['my_val'].shape[0] ) *min ( df1['my_val'] )
    for i, j, k, h in zip ( df1 ['th'], df1 ['pdvalue'], df1 ['my_val'], z2 ):
        ax.plot ( [i, i],  [j, j],  [k, h], color = color )

ax.set_xlabel ( 'th' )
ax.set_ylabel ( 'pdvalue' )
ax.set_zlabel ( 'my_val' )

# legend
plt.legend ( bbox_to_anchor=(1.05, 1), loc=2 )
plt.show ()

在此处输入图像描述


推荐阅读