【问题标题】:How to add a palette color into a scatterplot graph in R如何将调色板颜色添加到 R 中的散点图中
【发布时间】:2018-09-23 07:39:15
【问题描述】:

我想使用调色板(蓝色)中的颜色将颜色添加到散点图中。

  1. 数据示例

     tw = c(15000, 3000, 2500, 2000, 1500, 1500, 500)
     re.tw = c(8000, 6000, 5500, 3300, 700, 1000, 1500)
     Country = c('Argentina', 'Brasil', 'Mexico', 'Chile', 'Venezuela',   'Espana', 'EEUU')
     b = data.frame(tw,re.tw,Country)
     b$Ratio = as.integer((b$tw / b$re.tw)*1000)
    
  2. 散点图

      ggplot(b, aes(x=tw, y=re.tw)) + 
      geom_point(aes(col=Country, size=Ratio)) +
      theme_minimal() +
      xlim(c(0, 15000)) + 
      ylim(c(0, 8000)) + 
      labs(subtitle="by country, final values for #Hashtag", 
      y="Tweets", 
      x="Retweets", 
     title="Twetts Vs Retweets")
    
  3. 使用此代码的结果

  1. 预期结果 相同的图表,使用蓝色调色板

【问题讨论】:

  • 我不清楚。你想放弃每个国家的颜色吗?奇怪,因为这是在你的 subtitle 中。此外,查看您的代码,它相信您已经切换了 x 轴和 y 轴。
  • 由于这是我创建的几个图表之一,我想用相同的调色板(蓝色)来维护它,关于你的想法,是的,我把“Tweet”和“转推”在我的例子中。

标签: r scatter-plot color-palette


【解决方案1】:

我对您的代码做了一些小改动。

require(tidyverse)

# 1. Some values 
#Single command is usually better/simple than few commands. 
df = data.frame(tw = c(15000, 3000, 2500, 2000, 1500, 1500, 500),
               re.tw = c(8000, 6000, 5500, 3300, 700, 1000, 1500),
               Country = c('Argentina', 'Brasil', 'Mexico', 'Chile',
                           'Venezuela',   'Espana', 'EEUU')) %>%
  mutate(Ratio = (tw/re.tw)*100)


# 2. Scatterplot
df %>%
  #I find it easier to put all (or most) of the aes in one place
ggplot(aes(x = tw, y = re.tw, col = Country, size = Ratio)) + 
  geom_point() +
  #Setting the colors to palette Blues. 
  scale_color_brewer(palette = "Blues") +
  theme_minimal() +
  xlim(c(0, 15000)) + 
  ylim(c(0, 8000)) + 
  labs(subtitle="by country, final values for #Dante2018", 
       y="Tweets", 
       x="Retweets", 
       title="Twetts Vs Retweets", 
       caption = "Source: Tweets from January to April with #Dante2018")

更多关于scale_color_brewer你可以找到here

答案here 可能会帮助您为最大值设置一种特定颜色

【讨论】:

  • 谢谢。我从不使用包 tidyverse,我现在正在阅读它。你在代码中做了一个很棒的重构,我会检查每一个变化以便了解更多。再次感谢您。
  • tidyverse 包(以及其中的所有包)太棒了!如果您想了解有关 tidyverse/tidy-data 方法的更多信息,我建议您阅读此 (jstatsoft.org/article/view/v059i10/v59i10.pdf),您还可以观看此视频 (youtube.com/…) 和/或查找 Hadley Wickham 的内容(主要是) .此外,我很乐意提供帮助,如果此答案解决了您的问题,请单击答案旁边的复选标记将其标记为已接受。
猜你喜欢
  • 2020-05-25
  • 2020-10-29
  • 2019-05-14
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
相关资源
最近更新 更多