gpt4 book ai didi

r - 如何在 R 的 facet_wrap 标签中使用上标?

转载 作者:行者123 更新时间:2023-12-04 04:20:06 24 4
gpt4 key购买 nike

在我的 facet_label 中,我想使用上标,如下图 3 中的上标应该是 m。我也想在温度子图中用 C 分配度数符号。另外,我希望只在温度图中看到零水平线,而在流量和降水图中看不到。以下是我到目前为止的代码,如果有任何帮助,我将不胜感激。

library(tidyverse)
MonthlyData = data.frame(Month = 1:12, A = runif(12, 1,40), B = runif(12,-25,15), C = runif(12,-15,25), D = runif(12,1,75))
PlotData = gather(data = MonthlyData, key = "Variable", value = "Value", -Month)
PlotData$Variable = factor(PlotData$Variable, labels = c("Streamflow (m3/sec)", "Max temperature (oC)", "Min temperature (oC)", "Precipitation (mm)"))

ggplot(transform(PlotData, Variable = factor(Variable, levels = c("Streamflow (m3/sec)", "Precipitation (mm)", "Max temperature (oC)", "Min temperature (oC)"))), aes(x = Month, y = Value))+
geom_bar(stat = "identity", width = 0.5) + facet_wrap(~Variable, nrow = 4, scales = "free_y")+
geom_hline(yintercept = 0)+ aes(fill = as.factor(Variable))+
scale_x_continuous(breaks = c(1:12), labels = c("Jan", "Feb", "Mar","Apr", "May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"))+
theme_bw()

这是我根据示例数据绘制的图

enter image description here

最佳答案

使用来自 ggplot inserting space before degree symbol on axis label 的代码位, R - Interpreting a subscript in a variable used in ggplotHow to add different lines for facets我们可以到达那里:

library(ggplot2)
library(tidyr)

MonthlyData = data.frame(Month = 1:12, A = runif(12, 1,40), B = runif(12,-25,15),
C = runif(12,-15,25), D = runif(12,1,75))
PlotData = gather(data = MonthlyData, key = "Variable", value = "Value", -Month)

# To set the order of the facets, then create a factor for the facetting
# level in the order that you want
PlotData$Variable = factor(PlotData$Variable, levels=c("A", "D", "B", "C"))


# Set labels that are to be parsed
# use instead of changing Variable factor levels
# reorder to order of facet variable
lbs = setNames(c("'Streamflow ('*m^3*'/sec)'",
"'Max Temperature ' (degree*C)",
"'Min Temperature ' (degree*C)",
"Precipitation (mm)"),
LETTERS[1:4]
)[levels(PlotData$Variable)]

ggplot(PlotData, aes(x = Month, y = Value, fill = Variable)) +
geom_bar(stat = "identity", width = 0.5) +
# create facet labels from character vector
facet_wrap(~Variable, nrow = 4, scales = "free_y",
labeller=as_labeller(lbs, label_parsed)) +
# parse legend labels: reorder
scale_fill_discrete(labels = parse(text=lbs)) +
# specify names of facets to add horizontal line to
geom_hline(data=data.frame(Variable=c("B", "C")), aes(yintercept = 0))

要更改构面的顺序,请参阅 controlling order of facet_grid/facet_wrap in ggplot2?

关于r - 如何在 R 的 facet_wrap 标签中使用上标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59596250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com