【问题标题】:How do I make my ggplot2 graph display the top 20 percent of the distribution in a different color?如何让我的 ggplot2 图表以不同的颜色显示前 20% 的分布?
【发布时间】:2017-04-17 11:44:26
【问题描述】:

我正在使用RStudio 进行 R 编码。我有一个数据集(称为 mydata2),我正在使用这个数据框在 ggplot2 中构建一个绘图。

library(ggplot2)
mydata = read.csv("extrasjan15feb17.csv")
mydata2=mydata[(mydata$PropertyCode = "PLN" & mydata$Year==2016), ]

options(scipen=99)
ggplot(mydata2,aes(Year, TotalSpending)) + geom_jitter(size=2,alpha=0.5)+
scale_y_continuous(breaks=number_ticks(20), 
limits = c(min=0,max=254000))+
theme(axis.text.x=element_blank(),
axis.ticks.x=element_blank())

上面的代码给了我下面的情节:

基本上,图表显示了“mydata2”数据框的“TotalSpending”列中所有值的绘图。

现在,我的挑战是我希望这些值的前 20% 在图中以不同的颜色显示。我该如何应对这一挑战?

我正在考虑在数据框中创建一个新列,在分布中的每一行出现“前 20%”和“其他”等值,然后在我的 ggplot2 代码中使用该新列作为“颜色”的基础.但是,我不知道该怎么做。或者可能是我完全走错了路,还有另一种方法可以实现。

任何帮助将不胜感激。

【问题讨论】:

  • 尝试在aes()中添加color = TotalSpending > quantile(TotalSpending, prob = 0.8)

标签: r ggplot2


【解决方案1】:

您可以使用dplyrmutate 一个新列,以指示给定行是否在前 20% 中。您可以根据该行的值为数据点着色。

library(tidyverse) # Contains ggplot2 and so much more

# I don't have access to the CSV so here's some random data
mydata2 = tibble(TotalSpending = abs(rnorm(500)), Year = runif(500, min = 1900, max = 2000))

# I assume you're using this function from another StackOverflow answer?
number_ticks <- function(n) {function(limits) pretty(limits, n)}

# Create a new variable indicating whether or not a given value is in the top 20%
mydata2 <- mydata2 %>%
  mutate(top20 = percent_rank(TotalSpending) > 0.199)

# Specify color = top20 in aes()
options(scipen=99)
ggplot(mydata2,aes(Year, TotalSpending, color = top20)) + 
  geom_jitter(size=2,alpha=0.5)+
  scale_y_continuous(breaks=number_ticks(20), 
                     limits = c(min=0))+
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

我不熟悉函数number_ticks。我发现它在另一个 StackOverflow 问题中定义,所以我将该函数定义复制到我的答案中。

【讨论】:

  • 我也喜欢你的解决方案!
【解决方案2】:
# get a sample data
  data("mtcars")

# create dummy variable
  mtcars$percentile20 <- ifelse(mtcars$qsec > quantile(mtcars$qsec, 0.2), T, F)

# plot
  ggplot() +
       geom_point(data=mtcars, aes(hp, qsec, color=percentile20)) +
       scale_color_manual(values = c("black", "red"))

正如@Steven 在评论中提到的,如果你不想创建一个新列,你可以这样做,结果是一样的:

  ggplot() +
    geom_point(data=mtcars, aes(hp, qsec, color=qsec > quantile(qsec, prob=0.2))) +
    scale_color_manual(values = c("black", "red"))

【讨论】:

  • 不需要在数据中创建新列也不需要使用ifelse(),见我上面的评论。
猜你喜欢
  • 2016-09-14
  • 2021-05-31
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-19
  • 1970-01-01
相关资源
最近更新 更多