简体   繁体   中英

How to plot two independent variables with one being a top N count based on the dependent variable in R

Here is a sample of my dataset and I am attempting to create a bar chart using ggplot2 that shows the top N problems for each month. Using the sample dataset I would like to plot the top 3 problems for April 2018.

Month_Year  Problem             Problem_Count
April 2018  Parental consent    222
April 2018  Unable to download  53
April 2018  App restriction     105
April 2018  Website issue       99
April 2018  Account issue       17

Here is the code I have so far (it is based on the this question )

require(reshape2)
require(ggplot2)

ordered.results <- dataset$Problem_Count[order(dataset$Problem_Count, decreasing = TRUE)]

dfm <- melt(dataset, id.vars = c('Month_Year', 'Problem'))
dfm

csat <- ggplot(data = subset(dfm, Problem %in% ordered.results[1:5]) , aes(x=factor(Problem), y = value, fill = variable))
csat <- csat + geom_bar(stat='identity', width = 0.5, position = 'dodge')
csat <- csat + facet_grid(. ~ Month_Year)
csat <- csat + theme_bw()
csat <- csat + theme(axis.text.x = element_text(angle = 90))
csat

The issue I am having is being able to only plot the top N of each problem by month. Using this code I get the error Error: Faceting variables must have at least one value . Any help is much appreciated as I am very inexperienced with R. Thanks!

Credit for this goes to @aosmith. The issue was I was calling Problem and not value , which is part of melt(). Here is the fixed code.

ordered.results <- dataset$Problem_Count[order(dataset$Problem_Count, decreasing = TRUE)]

dfm <- melt(dataset, id.vars = c('Month_Year', 'Problem'))
dfm

csat.plot <- ggplot(data = subset(dfm, value %in% ordered.results[1:5]) , aes(x=factor(Problem), y = value, fill = variable))
csat.plot <- csat.plot +geom_bar(stat='identity', width = 0.5, position = 'dodge')
csat.plot <- csat.plot + facet_grid(. ~ Month_Year)
csat.plot <- csat.plot + theme_bw()
csat.plot <- csat.plot + theme(axis.text.x = element_text(angle = 90))
csat.plot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM