我想在同一个图上画一条曲线和一些小提琴图。是否可以 ? 目前,我只能单独绘制它们,一个在另一个的顶部,如示例代码中所示。
这是一个示例代码(使用
trim=TRUE
对齐效果更好,但我想保留 trim=FALSE
)
library("ggpubr")
library("ggplot2")
temps <- data.frame("LvlTemp"= c(rep("low", 10),
rep("medium", 15),
rep("high", 20)),
"Value" = c(runif(10, 0, 30), runif(15, 5, 40),runif(20, 15, 40) ))
df_E_old <- data.frame("Temp"=0:40, "dE_old"=sqrt(0:40))
Vplot <- ggplot(temps, aes(x = LvlTemp, y = Value, fill=LvlTemp, color=LvlTemp, alpha=0.5,
ymin=0, ymax = 40)) +
geom_violin(trim=FALSE) +
coord_flip() + # This switch X and Y axis and allows to get the horizontal version
xlab("") +
ylab("Temperature (°C)") +
theme(
legend.position="none" # no legend, don't know yet
) +
scale_x_discrete(limits=c("low", "medium", "high")) +
scale_color_manual(values=c("red", "blue", "purple"))+
scale_fill_manual(values=c("red", "blue", "purple"))
Lplot <- ggplot(df_E_old, aes(x=Temp, y=dE_old)) +
geom_line()
ggarrange(Vplot, Lplot,
ncol = 1, nrow = 2, align="v")
您可以尝试这种方法来组合 geom_violin() 和 geom_line():
library(ggplot2)
# Sample data
temps <- data.frame("LvlTemp"= c(rep("low", 10),
rep("medium", 15),
rep("high", 20)),
"Value" = c(runif(10, 0, 30), runif(15, 5, 40),runif(20, 15, 40)))
df_E_old <- data.frame("Temp"=0:40, "dE_old"=sqrt(0:40))
# Create a mapping for the x-axis that combines categorical and continuous variables
temps$LvlTemp <- factor(temps$LvlTemp, levels = c("low", "medium", "high"))
df_E_old$LvlTemp <- cut(df_E_old$Temp, breaks=c(0,10,20,40), labels=c("low","medium","high"))
# Create the plot
combined_plot <- ggplot() +
# Violin plot
geom_violin(data = temps, aes(x = LvlTemp, y = Value, fill = LvlTemp, color = LvlTemp),
alpha = 0.5, trim = FALSE) +
# Line plot, aligning the 'Temp' with the x-axis categories of the violin
geom_line(data = df_E_old, aes(x = Temp, y = dE_old), color = "black", size = 1) +
# Add labels and theming
xlab("Temperature Level") +
ylab("Temperature (°C) / dE_old") +
theme_minimal() +
theme(legend.position = "none") +
scale_color_manual(values = c("red", "blue", "purple")) +
scale_fill_manual(values = c("red", "blue", "purple"))
# Show the plot
print(combined_plot)