Reputation: 13
I'm trying to make a bar graph with ggplot and Shiny in R, but my data is structured in a weird way that seems to make this task more difficult than expected. The dataframe looks something like this:
Name Percent 1 Percent 2 Percent 3
A 45 10 45
B 30 20 50
C 10 35 55
Basically, I'd want to make my bar graph to show each percent as a "bar" based on what someone selects. For example, if my Shiny app has a dropdown menu that says "select name" and someone picks A, the resulting graphic should be three bars that show 45%, 10%, and 45%, with "Percent 1", "Percent 2", and "Percent 3" as the labels.
Thanks for any help!
Upvotes: 0
Views: 319
Reputation: 171
You first need to make sure that you have "tidy data" (= every variable goes in a column, and every column is a variable). In order to do that you can use the gather() function of the tidyr package; e.g.:
gather(stack, percent, value, -Name)
You can find out more information about tidy data here: https://r4ds.had.co.nz/tidy-data.html
Upvotes: 1
Reputation: 1728
I think you have to do some data tidying before you can do any visualization with this data. Here are some code sample that could do this job for you:
stack <- data.frame( name = c('A','B','C'),
percent1 = c(45,10,45),
percent2 = c(30,20,50),
percent3 = c(10,35,55),
stringsAsFactors = FALSE)
stack_ <- stack %>% gather(percent, value, percent1:percent3)
stack_ <- stack_ %>% filter(name == 'A')
p<-ggplot(data=stack_, aes(x=percent, y=value)) +
geom_bar(stat="identity")
p
Upvotes: 0