【问题标题】:Rscript in PowerBI for combined boxplot with bar chart (separate y-axis)PowerBI中的Rscript用于组合箱线图与条形图(单独的y轴)
【发布时间】:2020-07-23 19:04:40
【问题描述】:

Stackoverflow 和 R 都是菜鸟,所以请温柔一点!

我正在尝试使用 R 在 PowerBI 中创建一个图表,该图表将箱线图与时间序列 x 轴上的条形图相结合。看起来像这样的东西: Boxplot w Barchart(也在下方)。

我想要实现的是 x 轴,即周数 (Weeknum),条形图的 y 轴是“LDS”的计数,次要 y 轴是每单位成本“CAD_CPM”的英里范围。

我可以使用以下代码创建箱线图,但似乎无法弄清楚如何在条形图中添加。

非常感谢任何和所有帮助!谢谢!

boxplot (
CAD_CPM~Weeknum
,data=dataset
,main="Cost Per Mile (CAD)"
,outline = FALSE 
,ylab = "CPM (CAD)"
,xlab = ""
,col=(c("pink" , "light blue"))
    )

PowerBI boxplot(也在下方)

【问题讨论】:

  • 我不太了解在基础 R 中绘图,但 this post 可能会有所帮助

标签: r powerbi boxplot powerbi-desktop


【解决方案1】:

由于您没有提供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()

【讨论】:

  • 假设我想要在辅助 Y 轴上的箱线图 - 我将如何实现?谢谢!
猜你喜欢
  • 2018-09-16
  • 2017-08-06
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
相关资源
最近更新 更多