python - 改进我的“matplotlib.pyplot”语法以按目标散点图
问题描述
我有三维数据,其中一维是分类的:length
, width
, target
. 为简单起见,假设target
可以在{0, 1, 2}
. 我想绘制length
vs 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 = target
target
我想要类似的东西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")
为什么不发疯并同时使用hue
and style
!
我想正确的答案是“不要在里面做matplotlib
;在里面做seaborn
”。希望将错误标记为重复的问题得到解决,然后我可以添加包含完整详细信息的答案。
解决方案
那个怎么样:
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()
推荐阅读
- python - 如何在 Tensorflow 2 中实现小批量梯度下降?
- javascript - 如何对具有日期属性的对象数组进行排序?
- javascript - 在这个例子中我需要使用 var 变量还是 let 变量?
- python - 在 Colab 中将 NonType 转换为张量
- c# - 在我输入 C# 时将文本格式化为货币
- python - 尽管使用了allow_growth = True,为什么keras model.fit会使用这么多内存?
- json - 为什么 JSON 文本从 struct 转换为 JSON Swift 5 后的变量顺序与 struct 不同
- python - 如何将 sklearn 管道转换为 pyspark 管道?
- java - MailJet 无法从 java 电子邮件发送:( 400 Bad Request )
- python - 在嵌套回归器上使用 Pipeline 和 TransformedTargetRegressor 处理数据和目标缩放