由于您没有提供minimal reproducible example,因此我使用 R 中的 mtcars 数据集来说明我的观点。
在 PowerBI 的 R 脚本编辑器中尝试以下代码
library(ggplot2)
library(dplyr)
data = mtcars
temp <- data %>%
group_by(cyl = factor(cyl)) %>%
summarise(mpg = mean(mpg))
ggplot(data, aes(factor(cyl), mpg)) +
geom_bar(data = temp, aes(cyl, mpg), stat = "identity") +
geom_boxplot()+
theme_light()
将产生一个与条形图结合的箱线图,如下所示
现在,假设您想为这个情节添加一些香料,即制作一个彩色情节,然后尝试以下代码;
library(ggplot2)
library(dplyr)
data = mtcars
temp <- data %>%
group_by(cyl = factor(cyl)) %>%
summarise(mpg = mean(mpg))
str(temp)
ggplot(data, aes(factor(cyl), mpg)) +
geom_bar(data = temp, aes(cyl, mpg), stat = "identity",
fill=temp$cyl) +
geom_boxplot(aes(fill=factor(gear)))+
theme_light()
将导致以下情节;
添加辅助 y 轴可以通过使用 sec_axis() 函数来实现。请参阅official docs 了解更多信息。
library(ggplot2)
library(dplyr)
data = mtcars
temp <- data %>%
group_by(cyl = factor(cyl)) %>%
summarise(mpg = mean(mpg))
str(temp)
ggplot(data, aes(factor(cyl), mpg)) +
geom_bar(data = temp, aes(cyl, mpg), stat = "identity",
fill=temp$cyl) +
geom_boxplot(aes(fill=factor(gear)))+
scale_y_continuous("mpg (US)",
sec.axis = sec_axis(~ . * 1.20, name = "mpg (UK)"))+
theme_light()