ggplot2将多种图表类型组合为单个图表

时间:2019-01-29 06:09:32

标签: r ggplot2 scatter-plot boxplot ggplotly

我是R的新手,对ggplot2的组合着迷。在下面的代码中,我试图用数据集中的WAMP标签进行箱形图抖动。除了无法按大小对x轴排序并显示2个x轴值外,我似乎得到了大部分信息,类似这样的问题:Multi-row x-axis labels in ggplot line chart

这是我的R代码:

library(ggplot2)
library(plotly)

df <- data.frame(Products = rep(c('Product1','Product2','Product3'), times = 100),
                 Size = rep(c(1000,3000,2000), times = 100),
                 sales = runif(100, min=0, max = 300),
                 WAMP = rep(c(1.5,2.5,3.5), times = 100),
                 PricePerUnit = runif(100, min = 1, max = 5))

p <- ggplot() +
  geom_boxplot(data = df, aes(interaction(df$Size, df$Products, lex.order = TRUE), PricePerUnit, group = 1), outlier.colour = NULL) + 
  geom_jitter(data = df, aes(interaction(df$Size, df$Products, lex.order = TRUE), PricePerUnit, color = sales)) +
  scale_color_gradientn(colours = c("red", "yellow", "green", "lightblue", "darkblue")) +
  scale_y_continuous(breaks = seq(0, 10, by = .5)) +
  geom_line(data = df, aes(interaction(df$Size, df$Products, lex.order = TRUE), y = WAMP)) + 
  geom_text(data = df, aes(label = round(WAMP,2), x = Products, y = WAMP), size = 3) +
  ggtitle("Market by Price Distribution and Sales Volume")+
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
p <- ggplotly(p)
p

它将产生此图像,并且您可以看到它将WAMP图表放在箱线图抖动旁边(未合并)。任何帮助在这里都将不胜感激。谢谢。

Boxplot Jitter

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全明白,但是也许这就是您想要的?

p <- ggplot() +
    geom_boxplot(data = df, aes(interaction(df$Size, df$Products, lex.order = TRUE), PricePerUnit, group = 1), outlier.colour = NULL) + 
    geom_jitter(data = df, aes(interaction(df$Size, df$Products, lex.order = TRUE), PricePerUnit, color = sales)) +
    scale_color_gradientn(colours = c("red", "yellow", "green", "lightblue", "darkblue")) +
    scale_y_continuous(breaks = seq(0, 10, by = .5)) +
    geom_line(data = df, aes(interaction(df$Size, df$Products, lex.order = TRUE), y = WAMP)) + 
    geom_text(data = df, aes(label = round(WAMP,2), x = interaction(df$Size, df$Products, lex.order = TRUE), y = WAMP), size = 3) +
    ggtitle("Market by Price Distribution and Sales Volume")+
    theme(axis.text.x = element_text(angle = 45, hjust = 1))
p <- ggplotly(p)
p

只需要在geom_text右边指定x