Search code examples
rplotgraphhistogram

Insert X-axis labels into an R histogram (base hist package)


I have the below data frame in R:

enter image description here

I want to make a histogram with the accuracy rates for each of the three models. However, R isn't showing the X-axis labels (logistic, random forest, or SVM) - it is only showing the values below:

enter image description here

How can I add the x labels on the X axis to show which accuracy level relates to the respective model?

Thank you!

I tried the below code:

hist(accuracy_data_frame$Accuracy,seq(0.49,0.55,by=0.001))

Solution

  • You can use the command axis to add labels under the x-axis. I will give you two options with first histogram and second barplot. First the histogram which seems a bit tricky because the accuracy value of logistic and svm fall in the same bin. Because of that it only shows one label with is a problem. That's why I decided to do it also in a barplot. Here the code for in histogram:

    df <- data.frame(Accuracy = c(0.5419, 0.5231, 0.5464),
                     row.names = c("Logistic", "Random Forest", "SVM"))
    
    hist(df$Accuracy, seq(0.49,0.55,by=0.001))
    values <- c(df$Accuracy)
    labels <- c(row.names(df))
    axis(1, at = values, labels = labels, tick = FALSE, padj = 1.5)
    

    Output:

    enter image description here With the barplot it looks like this:

    barplot(df$Accuracy, ylim= c(0, 0.6))
    axis(1, at = 1:length(unique(df$Accuracy)), labels=unique(row.names(df)), padj = 1.5)
    

    Output:

    enter image description here

    The barplot seems to be a better option to show the accuracies of your models.