A.B*_*son 3 label r ggplot2 facet-wrap
我试图用表达式替换条形图facet_wrap上的标题ggplot,但我没有运气。我在这里和这里都试过,但似乎都不适合我。
整个数据集相当大,所以这里有一些虚拟数据来说明问题。
library(tidyr)
library(ggplot2)
data<-data.frame(species = rep(c("oak", "elm", "ash"), each = 5),
resp_1 = (runif(15, 1,100)),
resp_2 = (runif(15, 1,100)),
resp_3 = (runif(15, 1,100)),
resp_4 = (runif(15, 1,100)),
resp_5 = (runif(15, 1,100)))
### transform to longform with tidyr
data_2 <- gather(data, response, result, resp_1:resp_5, factor_key=TRUE)
### plot with ggplot2
ggplot(data_2, aes(x = species, y = result, fill = species))+
geom_bar(stat = 'sum')+
facet_wrap(~ response)
### here are the labels I'd like to see on the facets
oxygen <-expression ("Oxygen production (kg/yr)")
runoff <-expression("Avoided runoff " ~ (m ^{3} /yr))
co <- expression("CO removal (g/yr)")
o3 <- expression("O"[3]~" removal (g/yr)")
no2 <- expression("NO"[2]~" removal (g/yr)")
labels <- c(oxygen, runoff, co, o3, no2)
### this doesn't work
ggplot(data_2, aes(x = species, y = result, fill = species))+
geom_bar(stat = 'sum')+
facet_wrap(~ response, labeller = labeller(response = labels))
Run Code Online (Sandbox Code Playgroud)
### close, but doesn't work
levels(data_2$response)<-labels
ggplot(data_2, aes(x = species, y = result, fill = species))+
geom_bar(stat = 'sum')+
facet_wrap(~ response, labeller = labeller(response = labels))
Run Code Online (Sandbox Code Playgroud)
### produces an error
ggplot(data_2, aes(x = species, y = result, fill = species))+
geom_bar(stat = 'sum')+
facet_wrap(~ response, labeller = label_parsed)
Run Code Online (Sandbox Code Playgroud)
我还想摆脱标题为“n”的灰色第二个图例。
现在您的表达式名称与用作构面的值不匹配。所以我建议将您的标签存储在表达式中
labels <- expression(
resp_1 = "Oxygen production (kg/yr)",
resp_2 = "Avoided runoff " ~ (m ^{3} /yr),
resp_3 = "CO removal (g/yr)",
resp_4 = "O"[3]~" removal (g/yr)",
resp_5 = "NO"[2]~" removal (g/yr)"
)
Run Code Online (Sandbox Code Playgroud)
然后你可以编写自己的标签函数来提取正确的值
ggplot(data_2, aes(x = species, y = result, fill = species))+
geom_bar(stat = 'sum', show.legend = c(size=FALSE))+
facet_wrap(~ response, labeller = function(x) {
list(as.list(labels)[x$response])
})
Run Code Online (Sandbox Code Playgroud)
我们还使用show.legend = c(size=FALSE)到关闭n传奇
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |