如何将调色板颜色添加到R中的散点图图中

时间:2018-04-13 02:56:00

标签: r scatter-plot color-palette

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

  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. 使用此代码的结果

  4. enter image description here

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

1 个答案:

答案 0 :(得分:0)

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

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可能会帮助您为最大值设置一种特定颜色