【问题标题】:Need a solution on color problem with ggplot [duplicate]需要用ggplot解决颜色问题[重复]
【发布时间】:2021-12-30 09:55:38
【问题描述】:

我在可视化 ggplot 图表时遇到问题。我希望有不同颜色的不同间隔。

这是我的代码:

 ggplot(totalarum,aes(y=Pris,x=Boyta)+
 geom_point() + 
  xlim(100, 200) +
  ylim(1, 10000000) 

所以我想要的是一个关于如何得到的解决方案,例如 x

提前致谢!

【问题讨论】:

  • 请使用dput添加数据以重现问题

标签: r ggplot2 data-visualization


【解决方案1】:

如果您有两个间隔或只有一个条件,您可以将该条件映射到color 美学并通过scale_color_manual 设置您想要的颜色:

totalarum <- data.frame(
  Boyta = seq(0, 200, length.out = 20),
  Pris = seq(0, 10000000, length.out = 20)
)

library(ggplot2)

ggplot(totalarum, aes(y = Pris, x = Boyta, color = Boyta <= 100)) +
  geom_point() +
  scale_color_manual(values = c("TRUE" = "red", "FALSE" = "blue"))

编辑在更一般的情况下,您有多个间隔,我建议使用例如向您的数据集添加一个新列。 cut 然后可以映射到 color aes:

library(ggplot2)

totalarum <- data.frame(
  Boyta = seq(0, 500, length.out = 20),
  Pris = seq(0, 10000000, length.out = 20)
)
totalarum$Boyta_cut <- cut(totalarum$Boyta, breaks = seq(0, 500, 100), include.lowest = TRUE, right = TRUE)

colors <- c("red", "blue", "green", "purple", "steelblue")

ggplot(totalarum, aes(y = Pris, x = Boyta, color = factor(Boyta_cut))) +
  geom_point() +
  scale_color_manual(values = colors)

【讨论】:

  • 谢谢!如果我想要 0-100、100-200、200-300 和高达 500-600 之类的间隔?
  • 在更一般的情况下,您可以向数据集添加新列。查看我的编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 2021-07-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
相关资源
最近更新 更多