【问题标题】:How to add color to a plot based on a different column from a data set in R? [duplicate]如何根据与 R 中的数据集不同的列向绘图添加颜色? [复制]
【发布时间】:2021-05-12 15:48:06
【问题描述】:

大家,

我有以下数据集(称为演示)。

    Nation   GDP FHouse OECD   regime
1   Albania  3719    4.5    0 not free
2   Algeria  5327    5.5    0 not free
3    Angola  1462    6.0    0 not free
4 Argentina 12095    1.5    0     free
5   Armenia  2421    4.0    0 not free
6 Australia 27390    1.0    1     free

我做了一个图,绘制了一个 GDP 和 Fhouse 的图。

plot(demo$GDP, demo$FHouse, xlab = "Country's GDP", ylab = "Freedom House Rating", pch=16, xlim = c(500,5000), family="serif")

现在,我被要求根据制度(免费、非免费、部分免费)为每个点着色。我一直在阅读,显然我可以使用ifelse,但是我不知道如何给它三个条件,以便每个国家都根据免费,不免费和部分免费来着色。

谢谢大家。

【问题讨论】:

  • 一个更简单的方法是使用factors:plot(mpg ~ wt, mtcars, col = factor(gear))你也可以这样设置自定义颜色:plot(mpg ~ wt, mtcars, col = c('red', 'blue', 'orange')[factor(gear)])

标签: r plot


【解决方案1】:

如果您想继续使用基础 R 绘图,您可以这样做:

demo$color <- ifelse(demo$regime == 'free', 'red', 
                ifelse(demo$regime == 'not free', 'yellow', 'green'))

plot(demo$GDP, demo$FHouse, xlab = "Country's GDP", 
      ylab = "Freedom House Rating", pch=16, family="serif", col = demo$color)

ggplot2

library(ggplot2)
ggplot(demo) + 
  aes(GDP, FHouse, color = regime) + 
  geom_point() + 
  theme_bw()

【讨论】:

  • 这可能对switch(demo$regime, free="red", notfree="yellow", "green") 很有用。
  • 如果您已经设置了调色板,也可以使用factor - c("red","blue","black")[factor(demo$regime)] 甚至factor(demo$regime) 进行绘图
  • 开关不能只与标量一起使用吗?我猜我可能不得不使用switchsapply
  • 射击,对,...sapply(switch, demo$regime, free="red", ...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2021-03-24
  • 2016-11-18
  • 2012-08-04
  • 1970-01-01
相关资源
最近更新 更多