使用 ggplot2 在 R 中创建线性仪表:减少条形图宽度

Creating a linear gauge in R with ggplot2: reducing barplot width

我已经在 R 中创建了一个线性仪表,以便在 PowerBI 中显示。 我唯一的问题是绘图的宽度无法调整,所以我得到以下信息:

(绘图正在 PowerBI 中呈现)

而我想获得相同的图形,但宽度减半。 我尝试在 geom_bar 中使用宽度,但它会调整栏的大小并且最终输出是相同的。

理想情况下,条形图应为当前宽度的一半(我正在为 PowerBI 报告构建此图)。

这是我使用的代码:

library(ggplot2)

scores = factor(c('Inadequate','Adequate','Fair','Good','Great','Excellent','Exceptional'), 
       levels = (c('Inadequate','Adequate','Fair','Good','Great','Excellent','Exceptional')),
       ordered = TRUE)

x <- data.frame(points = rep(1,7), scores= scores)

x %>%
  ggplot(aes(x=points, fill=scores)) +
  geom_bar(position = "stack", show.legend = FALSE) +
  geom_text(aes(label=scores, y = seq(from=0.5, to=6.5, by = 1)), label.size = 0.25)+
  coord_flip() +
  theme(panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.line = element_blank(),
        axis.title = element_blank(),
        axis.ticks = element_blank(),
        axis.text = element_blank()) +
  geom_point(aes(x= 1.45, y=5), shape = 25, size=10, colour = "black", fill = "black") +
  geom_point(aes(x= 0.55, y=3), shape = 24, size=10, colour = "black", fill = "black") +
  geom_point(aes(x= 0.55, y=6), shape = 24, size=10, colour = "black", fill = "black") +
  scale_fill_brewer(palette = "RdYlGn", direction = -1)

如果无法简单地调整 Power BI 视觉对象的大小,您可以使用 theme(plot.margin = unit(c(0, 0.2, 0, 0.2), "npc")) 来增加 ggplot 在绘图周围绘制的边距。完整代码:

library(tidyverse)

scores = factor(c('Inadequate','Adequate','Fair','Good','Great','Excellent','Exceptional'), 
       levels = (c('Inadequate','Adequate','Fair','Good','Great','Excellent','Exceptional')),
       ordered = TRUE)

x <- data.frame(points = rep(1,7), scores= scores)

x %>%
  ggplot(aes(x=points, fill=scores)) +
  geom_bar(position = "stack", show.legend = FALSE) +
  geom_text(aes(label=scores, y = seq(from=0.5, to=6.5, by = 1)), label.size = 0.25)+
  coord_flip() +
  theme(panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.line = element_blank(),
        axis.title = element_blank(),
        axis.ticks = element_blank(),
        axis.text = element_blank()) +
  geom_point(aes(x= 1.45, y=5), shape = 25, size=10, colour = "black", fill = "black") +
  geom_point(aes(x= 0.55, y=3), shape = 24, size=10, colour = "black", fill = "black") +
  geom_point(aes(x= 0.55, y=6), shape = 24, size=10, colour = "black", fill = "black") +
  scale_fill_brewer(palette = "RdYlGn", direction = -1) +
  theme(plot.margin = unit(c(0, 0.2, 0, 0.2), "npc"))