如何在R中的face_wrap标签中使用上标?

问题描述 投票:2回答:1

在我的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

r ggplot2 subtitle facet-wrap superscript
1个回答
0
投票

使用ggplot inserting space before degree symbol on axis labelR - 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)

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

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
  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))
© www.soinside.com 2019 - 2024. All rights reserved.