2

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 Answer 1

5

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')

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.