python - 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()
解决方案
扩展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 ()
推荐阅读
- f# - F# 中强类型但用户可扩展的集合?
- reactjs - 使用反向方法时注意项目未删除
- python - bot whatsapp - 列表索引超出范围错误
- javascript - 如何在 ng-repeat 中使用过滤器?
- c++ - 如何制作一个接受任意等级数组的函数或构造函数
- python - 为什么这个程序总是在用户界面上响应没有响应消息?使用pycrypto的python代码
- reactjs - 在 React 中将切换类添加到 div
- node.js - 错误:values.map 不是函数(为什么会出现此错误)
- r - 合并模型摘要未显示 R 平方或调整后的 R 平方
- bash - 如何在变量中获取 curl 响应代码以及作为文件的输出,需要附加多个输出