ggplot在x轴上显示表达式 [英] ggplot displaying expression in x axis

查看:46
本文介绍了ggplot在x轴上显示表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面,我有R代码来绘制成组的条形图.

Below, I have R code that plots a grouped bar plot.

group_name = c('A_1x', 'A_1x', 'A_2x', 'A_2x', 'A_3x', 'A_3x', 'A_4x', 'A_4x')

mydata2 <- data.frame(mygroup = group_name, 
                      mysubgroup = factor(c("Yes", "No"), 
                                          levels = c("Yes", "No")), 
                      value = c(60,40,90,10,55,45,88,12))


ggplot(mydata2, aes(mygroup, value, fill = mysubgroup)) + 
  geom_bar(position = "dodge", width = 0.5, stat = "identity")+ 
  coord_flip() 

当前,该图如下所示.但是,我想在x轴上显示表达式,如下图所示.

Currently, the plot looks like below. However, I want to show expressions in the x axis as shown in the below picture.

我已经尝试过:

group_name = c(expression(A[1*x]),expression(A[1*x]),
               expression(A[2*x]),expression(A[2*x]),
               expression(A[3*x]),expression(A[3*x]),
               expression(A[4*x]),expression(A[4*x]))

但是它给出了以下错误:

But it gives the following error:

Error in as.data.frame.default(x[[i]], optional = TRUE) : 
  cannot coerce class ""expression"" to a data.frame

如何解决?

推荐答案

这里是一个有效的示例-我将 group_name 更改为4个元素,而不是8个,并将它们手动添加到了 ggplot中表达式.问题是表达式类型不能是 data.frame 的列名.这样可以解决这个问题.

Here is a working example - I changed the group_name to 4 elements instead of 8 and manually added them into the ggplot expression. The issue was that the expression type can't be a column name for a data.frame. This escapes that issue.

library(ggplot2)
group_name = c('A_1x', 'A_1x', 'A_2x', 'A_2x', 'A_3x', 'A_3x', 'A_4x', 'A_4x')
mydata2 <- data.frame(mygroup = group_name, 
                      mysubgroup = factor(c("Yes", "No"), 
                                          levels = c("Yes", "No")), 
                      value = c(60,40,90,10,55,45,88,12))

group_name = c(expression(A[1*x]),
               expression(A[2*x]),
               expression(A[3*x]),
               expression(A[4*x]))

ggplot(mydata2, aes(mygroup, value, fill = mysubgroup)) + 
  geom_bar(position = "dodge", width = 0.5, stat = "identity")+ 
  coord_flip() +
  scale_x_discrete(labels=group_name)  # Adding the labels here 

这篇关于ggplot在x轴上显示表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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