我想在我的直方图中绘制Voters_2009和Voters_2014,以便可以将它们进行比较。 我的数据是
S.No PC_Name Voters_2009 Voters_2014
1 Bastar 564742 769913
2 Bilaspur 770089 1090457
3 Durg 905900 1258342
4 Janjgir-Champa 737608 1073347
5 Kanker 742076 1016943
6 Korba 745617 1052720
7 Mahasamund 776337 1131209
8 Raigarh 935750 1246186
9 Raipur 741969 1250845
10 Rajnandgaon 830578 1178296
11 Sarguja 805197 1187321
DATA<-read.csv("CHATTISGARH FOR GEOJSON.csv")
ggplot(DATA,aes(x=PC_Name,y=Voters_2009))+geom_histogram(stat="identity")
我只能绘制Voters_2009或Voters2014。如何同时绘制它们?
答案 0 :(得分:1)
标准技巧是首先reshape the data from wide to long format,然后按照variable
美学进行分组。
library(ggplot2)
DATA_long <- reshape2::melt(DATA, id.vars = c("PC_Name", "S.No"))
ggplot(DATA_long, aes(PC_Name, value, fill = variable)) +
geom_bar(stat = "identity",
position = position_dodge()) +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
编辑。
如果图形条形图太满,则可能无法读取。构面是解决此问题的一种方法。当图形分为多个面时,fill
参数不再告诉哪一年是哪一年。
ggplot(DATA_long, aes(PC_Name, value, fill = variable)) +
geom_bar(stat = "identity",
position = position_dodge()) +
theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
facet_wrap(~ variable)
dput
格式的数据。
DATA <-
structure(list(S.No = 1:11, PC_Name = structure(1:11, .Label = c("Bastar",
"Bilaspur", "Durg", "Janjgir-Champa", "Kanker", "Korba", "Mahasamund",
"Raigarh", "Raipur", "Rajnandgaon", "Sarguja"), class = "factor"),
Voters_2009 = c(564742L, 770089L, 905900L, 737608L, 742076L,
745617L, 776337L, 935750L, 741969L, 830578L, 805197L), Voters_2014 = c(769913L,
1090457L, 1258342L, 1073347L, 1016943L, 1052720L, 1131209L,
1246186L, 1250845L, 1178296L, 1187321L)), class = "data.frame", row.names = c(NA,
-11L))
答案 1 :(得分:0)
代替
ggplot(DATA,aes(x=PC_Name,y=Voters_2009))+geom_histogram(stat="identity")
尝试
ggplot(DATA,aes(x=PC_Name))+
geom_histogram(aes(y=Voters_2009, color = 'red'), stat="identity") +
geom_histogram(aes(y=Voters_2014, color = 'blue'), stat="identity")