下面的代码制作了一个图表。有蓝色条,顶部有一条灰色线。目前,图例显示条形图为“当前月份”,但我想使用名为 reportYM1 的变量的值。我尝试输入不带引号的 reportYM1,但它显示为 reportYM1,而不是变量的值。由于某种原因,条形的颜色也变成了灰色而不是蓝色。
我错过了什么?
library(knitr)
library(markdown)
library(rmarkdown)
library(dplyr)
library(tidyr)
library(reshape2)
library(kableExtra)
library(shadowtext)
library(ggplot2)
library(RODBC)
library(lubridate)
library(formattable)
library(scales)
reportMonth = "2024-05-01"
reportMonth <- as.character(reportMonth[1,1])
reportYM1 = format(date(reportMonth), "%b %Y")
combinedDataA <- data.frame(category.x=c('HM_Admit_1_Percentage','HM_Admit_1_Percentage','HM_Admit_1_Percentage'),
valueP=c(0,0.0667,0.9333),
label=c('99221','99222','99223'),
category.y=c('HM_ytdAdmit_1_Percentage','HM_ytdAdmit_1_Percentage','HM_ytdAdmit_1_Percentage'),
valueH=c(0,0.1162791,0.8837209))
# Plotting
ggplot(data = combinedDataA, aes(x = label)) +
geom_bar(aes(y = valueP * 100, fill = "Current Month"), stat = "identity") +
geom_line(aes(y = valueH * 100, group = 1, color = "YTD"), size = 1) +
geom_point(aes(y = valueH * 100, color = "YTD"), size = 3) +
geom_shadowtext(aes(y = 0, label = scales::percent(valueP)), vjust = -0.5, color = "white", size = 3.5, bg.colour = "black", bg.r = 0.2) + # White text at the bottom of the bar
scale_y_continuous(
labels = scales::percent_format(scale = 1),
limits = c(0, 110),
expand = c(0, 0)
) +
scale_fill_manual(values = c("Current Month" = "#0060a9"), guide = guide_legend(title = NULL)) +
scale_color_manual(values = c("YTD" = "#bdbdb1"), guide = guide_legend(title = NULL)) +
labs(x = NULL, y = NULL, title = NULL, subtitle = NULL) +
theme_minimal() +
theme(legend.position = "bottom",
axis.text.x = element_text(angle = 0, hjust = 0.5),
axis.title.y = element_blank(),
axis.title.y.right = element_blank())
我没有
shadowtext
包,我相信它与你的问题无关,所以我不打算安装它。 这是一个基于 mtcars
数据集的 MRE,它允许您使用数据框中某一列的值来定义填充标签。 然而,这不是一种有效的做事方式,我不会推荐它。 相反,我要么编写一个自定义函数来允许您指定图例名称,要么提供一个(一行)控制数据集来执行相同的操作。
mtcars1 <- mtcars %>%
mutate(
gear_fact = as_factor(gear),
my_label = "A custom label"
)
mtcars1 %>%
ggplot() +
geom_bar(aes(y = cyl, fill = gear_fact)) +
scale_fill_discrete(name = mtcars1$my_label)