[英]Plot two box plots with same y variable but different x variables in ggplot2
[英]ggplot2 plots the two variables in the same plot but one variable with reversed y axis
我有以下示例數據:
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
dose=rep(c("D0.5", "D1", "D2"),2),
len=c(6.8, 15, 33, 4.2, 10, 29.5))
通常我們在同一個圖中繪制兩個變量VC
和OJ
,如下所示:
ggplot(data=df2, aes(x=dose, y=len, group=supp, colour=supp)) +
geom_line()
我想得到的是在反向 Y 軸上繪制VC
,同時仍將兩個變量保持在同一圖中並共享相同的 x 軸。 它應該像下圖:
我怎樣才能用 ggplot2 做到這一點? 非常感謝。
我不確定這是否是您要找的。
ggplot2,不太容易處理輔助軸。 為了反轉這個變量,需要乘以-1來反轉它。
library(tidyr)
#widen the dataframe, to separate the variables into different columns
df3<-pivot_wider(df2, id_cols = dose, names_from = supp, values_from = len)
ggplot(data=df3) +
geom_line(aes(x=dose, y=OJ, group="OJ", color="OJ")) +
geom_line(aes(x=dose, y=-1*VC, group="VC", color="VC"))
您可以將 supp == VC 的 len 值乘以 -1,然后照常繪制。 然后,使用scale_y_continuous
設置新的中斷和標簽。
library(dplyr)
library(ggplot2)
df2 %>%
mutate(len = ifelse(supp == "VC", len*-1,len)) %>%
ggplot(aes(x = dose, y = len, color = supp, group = supp))+
geom_point()+
geom_line()+
scale_y_continuous(limits = c(-40,40), breaks = seq(-20,20, by = 20),
labels = c(20,0,20))
這是您要找的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.