带有色度图和图例的Python 3D散点图 [英] 3D scatterplots in Python with hue colormap and legend
问题描述
我一直在用seaborn搜索python中的3D图,但没有看到.我想 3D 绘制我最初使用 seaborn pairplot 绘制的数据集.谁能帮我解决这两个问题:
- 我无法获得与 sns pairplot 相同的调色板,例如如何从图2获取调色板并将其应用于图1上的点?
- 图例不符合情节或在pairplot上显示不那么好,例如当我执行
plt.legend(bbox_to_anchor =(1.05,1),loc = 2,borderaxespad = 0.,ncol = 4)
时,我看到以下错误:anaconda2/lib/python2.7/site-packages/matplotlib/axes/_axes.py:545:UserWarning:找不到带标签的对象.在单个图上使用 label='...' kwarg.warnings.warn("未找到带标签的对象."
提前谢谢!我的参考资料:
#Seaborn 配对图df_3d = pd.DataFrame()df_3d['x'] = xdf_3d['y'] = ydf_3d['z'] = zsns.pairplot(df_3d,色相='x')
可以将来自 Seaborn 的调色板从
ListedColorMap
类的实例转换为 Matplotlib 颜色图,该类使用as_hex()
方法(如I have been searching for 3D plots in python with seaborn and haven't seen any. I would like to 3D plot a dataset that I originally plotted using seaborn pairplot. Can anyone help me with these 2 issues:
- I am not able to get same color palette as sns pairplot, e.g. how to get the color palette from figure 2 and apply to the points on figure 1?
- The legend does not stick to the plot or does not show up as nice on pairplot, e.g. When I do
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4)
I see the following error: anaconda2/lib/python2.7/site-packages/matplotlib/axes/_axes.py:545: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots. warnings.warn("No labelled objects found. "
Thanks in advance ! My references: How to make a 3D scatter plot in Python? https://pythonspot.com/3d-scatterplot/ https://jakevdp.github.io/PythonDataScienceHandbook/04.12-three-dimensional-plotting.html
Here's a MWE:
import re, seaborn as sns, numpy as np, pandas as pd, random from pylab import * from matplotlib.pyplot import plot, show, draw, figure, cm import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D sns.set_style("whitegrid", {'axes.grid' : False}) fig = plt.figure(figsize=(6,6)) ax = Axes3D(fig) # Method 1 # ax = fig.add_subplot(111, projection='3d') # Method 2 x = np.random.uniform(1,20,size=20) y = np.random.uniform(1,100,size=20) z = np.random.uniform(1,100,size=20) ax.scatter(x, y, z, c=x, marker='o') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show()
#Seaborn pair plot df_3d = pd.DataFrame() df_3d['x'] = x df_3d['y'] = y df_3d['z'] = z sns.pairplot(df_3d, hue='x')
解决方案The color palette from Seaborn can be turned into a Matplotlib color map from an instance of a
ListedColorMap
class initialized with the list of colors in the Seaborn palette with theas_hex()
method (as proposed in this original answer).From the Matplotlib documentation, you can generate a legend from a scatter plot with getting the handles and labels of the output of the
scatter
function.
The result of the code is shown in the picture below. Note that I generated more data points in order to better see that the colormap is the same. Also, the output of
ListedColorMap
outputs a color map with transparency variations, so I had to manually setalpha
to 1 in the scatter plot.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 # generate data n = 200 x = np.random.uniform(1, 20, size=n) y = np.random.uniform(1, 100, size=n) z = np.random.uniform(1, 100, size=n) # axes instance fig = plt.figure(figsize=(6,6)) ax = Axes3D(fig, auto_add_to_figure=False) fig.add_axes(ax) # get colormap from seaborn cmap = ListedColormap(sns.color_palette("husl", 256).as_hex()) # plot sc = ax.scatter(x, y, z, s=40, c=x, marker='o', cmap=cmap, alpha=1) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') # legend plt.legend(*sc.legend_elements(), bbox_to_anchor=(1.05, 1), loc=2) # save plt.savefig("scatter_hue", bbox_inches='tight')
这篇关于带有色度图和图例的Python 3D散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!