Search code examples
rggplot2plothistogram

How to plot an histogram for every row of a data frame (with the first column as a character value)


I am having difficulties in plotting a series of histograms to illustrate my data.

I have a data frame with topic prevalence for a number of documents. I would like to plot a group of histograms displaying topic prevalence for each document on the y axis. Every row would be its own histogram

This is how my data looks like:

meta1 Topic1 Topic2 Topic3 Topic4 Topic5
Doc1 0.296 1.06 0.0418 3.85 3.61
Doc2 2.06 1.07 0.223 1.57 2.18
Doc3 4.26 1.68 0.215 7.76 14.5
Doc4 1.72 23.6 0.900 3.53 1.41

This is what I have tried to do (I am really bad at using ggplot)

    plot2%>%
  keep(is.numeric) %>% 
  gather() %>% 
  ggplot(aes(value)) +
  facet_wrap(~ key, scales = "free") +
  geom_histogram()

And I get this error message:

Error in UseMethod("gather_") : 
  no applicable method for 'gather_' applied to an object of class "character"

I guess the problem is that the first column is a caracter vector. I would really appreciate any help with this!


Solution

  • If plot2 is the name of the dataframe try -

    library(tidyverse)
    
    plot2 %>%
      pivot_longer(cols = -meta1) %>%
      ggplot(aes(value)) +
      facet_wrap(~ meta1, scales = "free") +
      geom_histogram()