绘制散点图并根据ggplot2中的一个类别列设置颜色

时间:2020-06-26 05:45:44

标签: r ggplot2

给出如下数据框:

structure(list(city = structure(c(1L, 3L, 4L, 2L), .Label = c("bj", 
"cq", "sh", "tj"), class = "factor"), area = c(1580.86, 1927.95, 
532.24, 613.09), price = c(9.51, 94.42, 10.77, 8.58), level = structure(c(1L, 
1L, 2L, 2L), .Label = c("a", "b"), class = "factor")), class = "data.frame", row.names = c(NA, 
-4L))

我想绘制一个散点图,其中x的{​​{1}}和area的{​​{1}},同时,点的颜色仅基于{{1} },这意味着只有两种颜色可以区分yprice

我怎么能用level来画这个?谢谢。

1 个答案:

答案 0 :(得分:1)

您可以为此使用以下代码

library(ggplot2) 
ggplot(df, aes(x = area, y = price, col=level)) + geom_point()

enter image description here

ggplot(df, aes(x = area, y = price, col=level)) + 
  geom_point() + 
  ggrepel::geom_text_repel(aes(label = city))

enter image description here 数据

df=structure(list(city = structure(c(1L, 3L, 4L, 2L), .Label = c("bj", 
"cq", "sh", "tj"), class = "factor"), area = c(1580.86, 1927.95, 
532.24, 613.09), price = c(9.51, 94.42, 10.77, 8.58), level = structure(c(1L, 
1L, 2L, 2L), .Label = c("a", "b"), class = "factor")), class = "data.frame", row.names = c(NA, 
-4L))