简体   繁体   English

Python通过不同的数据框列进行绘图(使用Seaborn?)

[英]Python plotting by different dataframe columns (using Seaborn?)

I'm trying to create a scatterplot of a dataset with point coloring based on different categorical columns. 我正在尝试根据不同的分类列使用点着色创建数据集的散点图。 Seaborn works well here for one plot: Seaborn在这里适合一个情节:

fg = sns.FacetGrid(data=plot_data, hue='col_1')
fg.map(plt.scatter, 'x_data', 'y_data', **kws).add_legend()
plt.show()

I then want to display the same data, but with hue='col_2' and hue='col_3'. 然后,我想显示相同的数据,但使用hue ='col_2'和hue ='col_3'。 It works fine if I just make 3 plots, but I'm really hoping to find a way to have them all appear as subplots in one figure. 如果我仅绘制3个图,效果很好,但我真的希望找到一种方法,使它们全部显示为一个图形。 Unfortunately, I haven't found any way to change the hue from one plot to the next. 不幸的是,我还没有找到将色调从一种改变为另一种的方法。 I know there are plotting APIs that allow for an axis keyword, thereby letting you pop it into a matplotlib figure, but I haven't found one that simultaneously allows you to set 'ax=' and 'hue='. 我知道有些绘图API允许使用axis关键字,因此可以将其弹出到matplotlib图形中,但是我还没有找到可以同时设置'ax ='和'hue ='的图形API。 Any ideas? 有任何想法吗? Thanks in advance! 提前致谢!

Edit: Here's some sample code to illustrate the idea 编辑:这是一些示例代码来说明这个想法

xx = np.random.rand(10,2)
cat1 = np.array(['cat','dog','dog','dog','cat','hamster','cat','cat','hamster','dog'])
cat2 = np.array(['blond','brown','brown','black','black','blond','blond','blond','brown','blond'])
d = {'x':xx[:,0], 'y':xx[:,1], 'pet':cat1, 'hair':cat2}
df = pd.DataFrame(data=d)

sns.set(style='ticks')
fg = sns.FacetGrid(data=df, hue='pet', size=5)
fg.map(plt.scatter, 'x', 'y').add_legend()
fg = sns.FacetGrid(data=df, hue='hair', size=5)
fg.map(plt.scatter, 'x', 'y').add_legend()
plt.show()

This plots what I want, but in two windows. 这在两个窗口中绘制了我想要的图。 The color scheme is set in the first plot by grouping by 'pet', and in the second plot by 'hair'. 配色方案在第一个图中通过“ pet”分组进行设置,在第二个图中通过“ hair”进行设置。 Is there any way to do this on one plot? 有什么办法可以在一个情节上做到这一点吗?

In order to plot 3 scatterplots with different colors for each, you may create 3 axes in matplotlib and plot a scatter to each axes. 为了绘制3个散点图,每个散点图具有不同的颜色,您可以在matplotlib中创建3个轴,并将散点图绘制到每个轴上。

import pandas as pd
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.rand(10,5), 
                  columns=["x", "y", "col1", "col2", "col3"])

fig, axes = plt.subplots(nrows=3)
for ax, col in zip(axes, df.columns[2:]):
    ax.scatter(df.x, df.y, c=df[col])

plt.show()

在此处输入图片说明

For categorical data it is often easier to plot several scatter plots, one per category. 对于分类数据,通常更容易绘制多个散点图,每个类别一个。

import pandas as pd
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import seaborn as sns


xx = np.random.rand(10,2)
cat1 = np.array(['cat','dog','dog','dog','cat','hamster','cat','cat','hamster','dog'])
cat2 = np.array(['blond','brown','brown','black','black','blond','blond','blond','brown','blond'])
d = {'x':xx[:,0], 'y':xx[:,1], 'pet':cat1, 'hair':cat2}
df = pd.DataFrame(data=d)


cols = ['pet',"hair"]
fig, axes = plt.subplots(nrows=len(cols ))
for ax,col in zip(axes,cols):
    for n, group in df.groupby(col):
        ax.scatter(group.x,group.y, label=n)
    ax.legend()

plt.show()

在此处输入图片说明

You may surely use a FacetGrid, if you really want, but that requires a different data format of the DataFrame. 如果确实需要,可以肯定使用FacetGrid,但这需要DataFrame的其他数据格式。

import pandas as pd
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import seaborn as sns

xx = np.random.rand(10,2)
cat1 = np.array(['cat','dog','dog','dog','cat','hamster','cat','cat','hamster','dog'])
cat2 = np.array(['blond','brown','brown','black','black','blond','blond','blond','brown','blond'])
d = {'x':xx[:,0], 'y':xx[:,1], 'pet':cat1, 'hair':cat2}
df = pd.DataFrame(data=d)

df2 = pd.melt(df, id_vars=['x','y'], value_name='category', var_name="kind")

fg = sns.FacetGrid(data=df2, row="kind",hue='category', size=3)
fg.map(plt.scatter, 'x', 'y').add_legend()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM