使用ggplot2

时间:2019-10-27 09:23:49

标签: r ggplot2

我是R的新手,正在尝试绘制数据点。有单个条形图的解决方案,但似乎并没有一个解决方案。

# Data 
pills= c("a","b","c","d") 

#control data
pill_a_control = c(5,90,10,65) 
pill_b_control = c(2,12,23,9)
pill_c_control = c(87,120,50,22) 
pill_d_control = c(34,50,100,70) 

# test data 
pill_a_test = c(90,89,3,66,88,50) 
pill_b_test = c(99,78,67,88,70,88) 
pill_c_test = c(34,100,90,45,55,67) 
pill_d_test = c(94,70,34,56,76,78) 

#control & test mean 
pill_a_control_mean=mean(pill_a_control) 
pill_a_test_mean=mean(pill_a_test) 
pill_b_control_mean=mean(pill_b_control) 
pill_b_test_mean=mean(pill_b_test) 
pill_c_control_mean=mean(pill_c_control) 
pill_c_test_mean=mean(pill_c_test)
pill_d_control_mean=mean(pill_d_control) 
pill_d_test_mean=mean(pill_d_test)

# organize test & control into a table pill_test_mean=cbind(pill_a_test_mean,pill_b_test_mean,pill_c_test_mean,pill_d_test_mean) 
pill_control_mean=cbind(pill_a_control_mean,pill_b_control_mean,pill_c_control_mean,pill_d_control_mean) 
pill_control_mean=as.numeric(pill_control_mean)
pill_test_mean=as.numeric(pill_test_mean)  
df_wide=cbind(pills,pill_control_mean,pill_test_mean)
df_long=gather(data.frame(df_wide),types,level,pill_control_mean:pill_test_mean, factor_key=TRUE)

# plot 
plot= ggplot(data=df_long, aes(x= pills, y=level, fill=types)) + geom_bar(stat="identity", position=position_dodge()) + scale_fill_discrete(name = "Pills", labels = c("Control", "Test")) +  xlab("Pills") + ylab("level of X")

我的问题是,如何为每一列添加数据点? (请不要更改现有代码)

1 个答案:

答案 0 :(得分:0)

您可以使用facet_wrap()

ggplot(data=df_long, aes(x= pills, y=level, fill=types)) + 
geom_bar(stat="identity", position=position_dodge()) + 
scale_fill_discrete(name = "Pills", labels = c("Control", "Test")) +  
xlab("Pills") + ylab("level of X")+
facet_wrap(facets = ~types)

enter image description here