我如何制作一个带有两个变量的图,如图中的那个

时间:2017-09-10 09:49:24

标签: r

我有这个数据框 I have this data frame

我想用ggplot2制作一个类似的情节 I want to make a plot like it with ggplot2

我应该使用哪个功能?或者这个剧情的名称

1 个答案:

答案 0 :(得分:1)

这会给你一个类似的情节。

library(ggplot2)
library(ggrepel)

#sample data
df <- data.frame(Age_Range = c('M.25-34', 'M.18-24', 'M.13-17', 'F.25-34', 'F.18-24', 'F.13-17'),
                 Count = c(3356, 2071, 15, 5619, 4342 ,29))

#pre-process dataframe so that it can be used with ggplot2
df$Sex <- gsub('(\\S).*', '\\1',df$Age_Range)
df$Age <- gsub('\\S{2}(.*)', '\\1',df$Age_Range)

#plot
ggplot(df, aes(x= Age, y= (Count/sum(Count))*ifelse(Sex=="F",1,-1), fill=Sex)) + 
  geom_bar(stat="identity", position = "identity") +
  geom_text_repel(aes(y = (Count/sum(Count))*ifelse(Sex=="F",1,-1), label=paste0(round(Count/sum(Count)*100, digits = 2),"%"))) +
  ylab("Your fans") +
  ggtitle("The people who like your Page") +
  theme(axis.text.y=element_blank())


希望这有帮助!