如何在ggplot中为标签添加表达式
How to add expression to label in ggplot
我已经能够添加基于方面的标签,但是,如何将其标签设为文本:
"Mean = 0.235" 而不仅仅是“0.235”
这是我的 ggplot
,其中重要的部分是 geom_text
:
ggplot(data = filter(season_melt,(HOUSEHOLD_ID_ANONYMISED %in% c(37218002754,37218032412, 38443537620))), aes(factor(HOUSEHOLD_ID_ANONYMISED), value)) +
geom_boxplot(aes(fill = factor(HOUSEHOLD_ID_ANONYMISED))) +
facet_wrap(~Season) +
theme(text = element_text(size=40), legend.position = "none") +
xlab("Household ID") +
ylab("Usage") +
geom_hline(data = mean_season, aes(yintercept = Mean), size = 1, colour = "blue", linetype = "dashed") +
geom_text(data = mean_season, aes(0,Mean,label = round(Mean,3), vjust = -1, hjust = -0.1), color = "blue", size = 11)
这是一张图片,显示了每个方面的标签:
你有(至少)两个选择。
创建合适的字符串
# Something like
geom_text(data = mean_season,
aes(0, Mean, label = sprintf('Mean = %0.3f', Mean),
vjust = -1, hjust = -0.1),
color = "blue", size = 11)
# or
geom_text(data = mean_season,
aes(0, Mean, label = paste('Mean = ',round(Mean, 3)),
vjust = -1, hjust = -0.1),
color = "blue", size = 11)
在对 geom_text
的调用中使用 parse=TRUE
。在这种情况下,您需要根据 ?plotmath
(和 ?geom_text
)
构造适当的表达式
geom_text(data = mean_season, parse = TRUE
aes(0, Mean, label = paste('Mean ==',round(Mean, 3)),
vjust = -1, hjust = -0.1),
color = "blue", size = 11)
选项 2 将在可视化时创建 "nicer" 外观表达式。
我已经能够添加基于方面的标签,但是,如何将其标签设为文本:
"Mean = 0.235" 而不仅仅是“0.235”
这是我的 ggplot
,其中重要的部分是 geom_text
:
ggplot(data = filter(season_melt,(HOUSEHOLD_ID_ANONYMISED %in% c(37218002754,37218032412, 38443537620))), aes(factor(HOUSEHOLD_ID_ANONYMISED), value)) +
geom_boxplot(aes(fill = factor(HOUSEHOLD_ID_ANONYMISED))) +
facet_wrap(~Season) +
theme(text = element_text(size=40), legend.position = "none") +
xlab("Household ID") +
ylab("Usage") +
geom_hline(data = mean_season, aes(yintercept = Mean), size = 1, colour = "blue", linetype = "dashed") +
geom_text(data = mean_season, aes(0,Mean,label = round(Mean,3), vjust = -1, hjust = -0.1), color = "blue", size = 11)
这是一张图片,显示了每个方面的标签:
你有(至少)两个选择。
创建合适的字符串
# Something like geom_text(data = mean_season, aes(0, Mean, label = sprintf('Mean = %0.3f', Mean), vjust = -1, hjust = -0.1), color = "blue", size = 11) # or geom_text(data = mean_season, aes(0, Mean, label = paste('Mean = ',round(Mean, 3)), vjust = -1, hjust = -0.1), color = "blue", size = 11)
在对
构造适当的表达式geom_text
的调用中使用parse=TRUE
。在这种情况下,您需要根据?plotmath
(和?geom_text
)geom_text(data = mean_season, parse = TRUE aes(0, Mean, label = paste('Mean ==',round(Mean, 3)), vjust = -1, hjust = -0.1), color = "blue", size = 11)
选项 2 将在可视化时创建 "nicer" 外观表达式。