Combining horizontal bars with facet_grid in ggplo

2019-05-20 03:05发布

问题:

I'd like to combine a horizontal bar plot with facet_grid. Thereby it should only show categories which occur for a certain group. I give you an example here, which will express my wish more concretely.

Here's some example data for your convenience:

visual_data=data.frame(Values = 10:1, Words = c("yeah","what","is","up","and","how", "are", "things","for", "you"), group = c("a","b","a","b","a","b","a","b","a","b"))

I want this type of plot:

graphic=ggplot(visual_data, aes(x=Values, y=reorder(Words,Values)))
graphic=graphic + geom_point() +
  ylab("Word") + 
  xlab("Count of occurences") +
  ggtitle("Frequency") +
  facet_grid(group~., scales = "free")
graphic

only with bars, which does not work (s. below what exactly does not work):

graphic=ggplot(visual_data, aes(y=Values, x=reorder(Words,Values)))
graphic=graphic + geom_bar(stat="identity") + 
  ylab("Word") + 
  xlab("Count of occurences") +
  coord_flip() +
  ggtitle("Frequency") +
  facet_grid(group~., scales = "free")
graphic

The difference lies in the displayed categories in the vertical axis. In the first plot only categories which occur in a group appear, while in the second plot all categories appear for each category.

回答1:

Strange - maybe a bug? As a quick&dirty workaround, you could use segments:

ggplot(visual_data, aes(xend=Values, x=0, y=reorder(Words, Values), yend=reorder(Words, Values))) +
  geom_segment(size=10, color="#303030") + 
  facet_grid(group~., scales = "free")


标签: r ggplot2