问题
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
回答1:
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')

来源:https://stackoverflow.com/questions/28462368/how-to-label-an-axis-with-several-variables-in-r-ggplot2