如何在ggplot2中将表达式设置为构面的轴文本? [英] How to set expressions as axis text of facets in ggplot2?

查看:95
本文介绍了如何在ggplot2中将表达式设置为构面的轴文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在ggplot2中的构面环境中将表达式设置为x轴文本,且标签长度不相等.例如:

I am trying to set expressions as x-axis text in facet environment in ggplot2 with unequal length of labels. For example:

dat <- structure(list(Species = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L, 2L), .Label = c("A", "B"), class = "factor"), Individual = structure(c(1L, 
2L, 3L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c("1", "2", "3", "4", 
"expression(bar(\"x\"))"), class = "factor"), mean = c(45, 32, 
100, 59, 65, 110, 87, 93, 88.75), min = c(34, 20, 89, 47.66666667, 
54, 100, 67, 85, 76.5), max = c(54, 42, 110, 68.66666667, 76, 
120, 99, 105, 100)), .Names = c("Species", "Individual", "mean", 
"min", "max"), class = "data.frame", row.names = c(NA, -9L))

require(ggplot2)

此答案介绍了如何做到这一点.我设法设置了labels,但是我找不到如何分别为每个构面设置标签的方法:

This answer describes how to do it without facets. I manage set the labels, but I cannot find how to set labels for each facet separately:

ggplot(dat, aes(x = Individual, y = mean, ymin = min, ymax = max, color = Species)) + 
  geom_pointrange() + 
  facet_wrap(~Species, scales = "free") + 
  scale_x_discrete(labels = c("1", "2", "3", expression(bar("x")))) + 
  theme_grey(base_size = 18)

长矢量或指定labels的列表似乎不起作用:

A long vector or a list specifying labels does not seem to work:

ggplot(dat, aes(x = Individual, y = mean, ymin = min, ymax = max, color = Species)) + 
  geom_pointrange() + 
  facet_wrap(~Species, scales = "free") + 
  scale_x_discrete(labels = c("1", "2", "3", expression(bar("x")), "1", "2", "3", "4", expression(bar("x")))) +
  theme_grey(base_size = 18)

ggplot(dat, aes(x = Individual, y = mean, ymin = min, ymax = max, color = Species)) + 
  geom_pointrange() + 
  facet_wrap(~Species, scales = "free") + 
  scale_x_discrete(labels = list(c("1", "2", "3", expression(bar("x")), c("1", "2", "3", "4", expression(bar("x")))))) + 
  theme_grey(base_size = 18)

ggplot2中有办法吗?

推荐答案

您可以将breaks参数添加到scale_x_discrete:

You can add the breaks arguments to scale_x_discrete:

ggplot(dat, aes(x=Individual, y = mean,ymin = min, ymax = max, color=Species)) + 
geom_pointrange() + facet_wrap(~Species, scales = "free_x") +
scale_x_discrete(breaks=levels(factor(dat$Individual)),
               labels = c("1", "2", "3", "4", expression(bar("x")))) +
theme_grey(base_size = 18)

这篇关于如何在ggplot2中将表达式设置为构面的轴文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆