首页 > 解决方案 > 改进我的“matplotlib.pyplot”语法以按目标散点图

问题描述

我有三维数据,其中一维是分类的:length, width, target. 为简单起见,假设target可以在{0, 1, 2}. 我想绘制lengthvs width"by" target。根据目标值,这些点将具有不同的颜色和形状。

我可以在 中执行此操作matplotlib.pyplot,导入为plt,使用以下语法。我假设 apandas DataFrame df具有我强加的结构。

X0 = df.query("target == 0.0").drop("target", axis = 1)
X1 = df.query("target == 1.0").drop("target", axis = 1)
X2 = df.query("target == 2.0").drop("target", axis = 1)

ax = plt.axes()
X0.plot(x = "length", y = "width", kind = "scatter", ax = ax, color = "red")
X1.plot(x = "length", y = "width", kind = "scatter", ax = ax, color = "blue")
X2.plot(x = "length", y = "width", kind = "scatter", ax = ax, color = "green")
plt.show()

我相信我们都同意这是bbaaaddd

几年前,我曾经在R. 该ggplot2包允许以下形式的语法

ggplot(df, x = length, y = width, shape = target).geom_point().

可以根据 的值替换shape = target为以获得不同的颜色。colour = targettarget

我想要类似的东西pyplot。尽我所能,我无法在文档或在线资源中找到此类信息。我敢肯定它一定在某个地方。我只是一直找不到它...


编辑。 此问题已标记为重复。这些副本有助于解决一些问题,但它们并不能解决上面提出的所有问题。特别是,没有讨论形状。我发现最接近的是以下问题:如何根据列变量更改标记的形状?. 还有其他类似的问题。shape = "target"但与简单的调用相比,这非常难看。

有一个“ggplot for python”包,名为plotnine,但它似乎已经 5 年没有更新了。您似乎还需要做类似的事情from plotnine import *,我当然不会对此感到兴奋。

也许我所追求的功能在pyplot. 如果是这样,这就是生活!:)


编辑。@Trenton McKinney 建议使用seaborn, 导入为sns. 这有一个hue选项,可以精确地进行不同的着色。

sns.scatterplot(data = df, x = "length", y = "width", hue = "target")

这仍然没有回答我关于形状的问题——(部分)“重复”也没有。但是,sns.scatterplot也有一个选项,除了“不同的颜色”被“不同的标记”替换之外style,它具有相同的描述。hue

sns.scatterplot(data = df, x = "length", y = "width", style = "target")

为什么不发疯并同时使用hueand style

我想正确的答案是“不要在里面做matplotlib;在里面做seaborn”。希望将错误标记为重复的问题得到解决,然后我可以添加包含完整详细信息的答案。

标签: pythonmatplotlibscatter-plot

解决方案


那个怎么样:

for target in [0.0, 1.0, 2.0]:
    df.query("target == " + str(target)).drop("target", axis = 1).plot(x = 
        "length", y = "width", kind = "scatter")
plt.show()

推荐阅读