3

我根据价格变量过滤了菱形数据框,以使价格低于或等于 10000,并将新数据框命名为 df。

然后,我添加了一个具有价格列分位数的新列分位数。最高价格位于第 1 个分位数(前 20%),最低价格位于第 5 个分位数。

Q1 定义了用于绘制不同分位数之间的垂直线的值。

library(ggplot2)
library(dplyr)
df <- diamonds %>% filter(price <= 10000)
df <- within(df, quantile <- 6 - as.integer(cut(price, quantile(price, probs=0:5/5), include.lowest=TRUE)))
df$quantile<-factor(df$quantile, levels=c("1", "2", "3", "4", "5","6", "7", "8", "9","10"))
Q1 <- quantile(df$price, 1:4/5)


ggplot(df, aes(x=price, y= carat, color=quantile))+
       geom_point(alpha=0.4, size=1)+ 
       geom_vline(xintercept=Q1, alpha=0.5, linetype="longdash")+ 
       geom_text(aes(x=5000, y=2,
                 label="80th %ile"), hjust=1, vjust= 1, angle =90, colour="blue") +
       geom_text(aes(x=2850, y=2,
                 label="60th %ile"),
                 hjust=1, vjust= 1, angle =90, colour="blue")+
       geom_text(aes(x=820, y=2,
                 label="20th %ile"),
                 hjust=1, vjust= 1, angle =90, colour="blue")+
       facet_wrap(~cut, ncol=2, scales="free_y")+
       theme_bw()+
       labs(x="Price ($)", y="Carat")

由于 facet_wrap 中的刻度,垂直线的标签没有对齐。此外,标签与点重叠,如下所示 在此处输入图像描述

我通过删除 facet_wrap 中的 scales="free_y" 并在 geom_text 中将 y 更改为 3 来解决这个问题

在此处输入图像描述 在前面的图中,它工作得很好,因为 y 值在钻石切割级别之间变化不大。

但是,如果我有一个 y 值完全不同的数据框,那么我无法修复 geom_text 中的 y 值。

当我在 facet_wrap 中有不同的 y 值而不删除 scales="free_y" 时,有什么方法可以对齐垂直线的标签?

4

1 回答 1

3

这个怎么样?

library(ggplot2)
library(dplyr)
df <- diamonds %>% filter(price <= 10000)
df <- within(df, quantile <- 6 - as.integer(cut(price, quantile(price, probs=0:5/5), include.lowest=TRUE)))
df$quantile<-factor(df$quantile, levels=c("1", "2", "3", "4", "5","6", "7", "8", "9","10"))
Q1 <- quantile(df$price, 1:4/5)

lbl <- data.frame(cut = c("Ideal", "Premium", "Very Good", "Good", "Fair"),
                  y_offset = c(max(df$carat[df$cut == "Ideal"]) * 0.6,
                               max(df$carat[df$cut == "Premium"]) * 0.6,
                               max(df$carat[df$cut == "Very Good"]) * 0.6,
                               max(df$carat[df$cut == "Good"]) * 0.6,
                               max(df$carat[df$cut == "Fair"]) * 0.6))

ggplot()+
  geom_point(data = df, aes(x=price, y= carat, color=quantile), alpha=0.4, size=1)+ 
  geom_vline(data = df, xintercept=Q1, alpha=0.5, linetype="longdash")+ 
  geom_text(data = lbl, aes(x=5000, y=y_offset,
                            label="80th %ile"), hjust=1, vjust= 1, angle =90, colour="blue") +
  geom_text(data = lbl, aes(x=2850, y=y_offset,
                            label="60th %ile"),
            hjust=1, vjust= 1, angle =90, colour="blue")+
  geom_text(data = lbl, aes(x=820, y=y_offset,
                            label="20th %ile"),
            hjust=1, vjust= 1, angle =90, colour="blue")+
  facet_wrap(~cut, ncol=2, scales="free_y")+
  theme_bw()+
  labs(x="Price ($)", y="Carat")
于 2016-01-18T02:04:28.563 回答