如何用R ggplot2中的多个变量标记轴 [英] How to label an axis with several variables in R ggplot2

查看:850
本文介绍了如何用R ggplot2中的多个变量标记轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框如下:

 名称,导师,测试,分数,百分比,school.year 
Mark,Eric,Maths,100,100,2
Mark,Eric,英语,91,91,2
Sue,Richard,Maths,88,100,5
Sue,Richard,英语,71, 80.7,5

我想在y轴上绘制百分比,在x轴上绘制条形图为每个测试。我的代码做我想要的情节,但x轴标签只是名称。我想在x轴上添加其他变量(仅用于标签)。所以比如标有2个小节; 1代表数学,1代表英语,他的xaxis标签也有'mark''\\''Eric'的标注,所以我们可以看到谁指导了他。如果可能的话,我想添加几个额外的标签,如学年。我的代码到目前为止如下;

 结果<  -  read.csv('results.csv')
p < - ggplot(results,aes(y = Percent,x = Name,color = Test,fill = Test))+
geom_bar(stat ='identity',position ='dodge')+
ggtitle('Test Results')+
ylab('Percent')

例如:

  + scale_x_discrete(labels = results $ Score)




$ b

或手动更改它们(尽管订单有问题);

p> scale_x_discrete(labels = c('Mark \\\
Eric','Sue \ Richard',等等))

有没有办法添加其他变量到X标签,最好是换行符?非常感谢

解决方案

我建议在数据框中创建另一列,其中包含标签,然后将其用作 x

  results $ label<  -  paste(results $ Name ,结果$ Tutor,sep ='\\\
')

ggplot(results,aes(y = Percent,x = label,color = Test,fill = Test))+
geom_bar ('stat'='identity',position ='dodge')+
ggtitle('Test Results')+
ylab('Percent')


I have a dataframe as follows:

 Name,Tutor,Test,Score,Percent,school.year
 Mark,Eric,Maths,100,100,2
 Mark,Eric,English,91,91,2
 Sue,Richard,Maths,88,100,5
 Sue,Richard,English,71,80.7,5

I would like to plot percent on the y axis and name on the x axis with bars for each test. My code does the plot how I would like but the x-axis label is just the name. I would like to add other variables (just to the label) in the x-axis. So for example mark with have 2 bars; 1 for maths and 1 for english, his xaxis label with also say 'mark' '\n' 'Eric' so we can see who tutored him. If possible I would like to add several additional labels such as school year. My code so far is as follows;

 results <- read.csv('results.csv')
 p <- ggplot(results, aes(y=Percent, x=Name, colour=Test, fill=Test)) + 
 geom_bar(stat='identity', position='dodge') + 
 ggtitle('Test Results') + 
 ylab('Percent')

I can plot a single variable as the x-axis label e.g:

 +scale_x_discrete(labels = results$Score)

or change them manually (although there are problems with the order);

scale_x_discrete(labels = c('Mark \n Eric','Sue \n Richard', etc))

Is there a way to add other variables to the x-labels, ideally with line breaks? Many thanks

解决方案

I'd suggest to create another column in your data frame, which will contain labels, and then use it as x:

results$label <- paste(results$Name,results$Tutor,sep='\n')

ggplot(results, aes(y=Percent, x=label, colour=Test, fill=Test)) +
  geom_bar(stat='identity', position='dodge') +
  ggtitle('Test Results') +
  ylab('Percent')

这篇关于如何用R ggplot2中的多个变量标记轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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