【问题标题】:How do I insert one more column in my Histogram and plot it on Y axis如何在直方图中再插入一列并将其绘制在 Y 轴上
【发布时间】:2019-07-03 09:46:46
【问题描述】:

我想在我的直方图中绘制 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 或 Voters 2014。如何同时绘制它们?

【问题讨论】:

  • 请不要以图片形式发布数据(或代码),请以dput 格式发布。请用dput(DATA) 的输出编辑问题。
  • @RuiBarradas 你能帮我吗? dput 有什么用?我必须以代码格式复制粘贴我的数据吗?
  • 是的,这是首选方式。像这样,我们可以简单地复制并粘贴到会话中以创建数据集。
  • 你想要直方图还是条形图?
  • @RuiBarradas 他们中的任何一个都可以工作

标签: r csv


【解决方案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))

【讨论】:

  • 如何更改我的全部数据?
  • {library(ggplot) DATA_long &lt;- reshape2::melt(DATA2, 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))
  • 我更改了我的数据框,但它返回了相同的图表,为什么?
  • 它跑了。但我有一个新问题。有一个大酒吧我不知道为什么prntscr.com/o9zcmo。我现在已经为我的整个数据计算了图表。
  • 试着看看哪个值大于,比如说,2500000。鉴于图表,也许最好按年分面,看看编辑。
【解决方案2】:

代替

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")

【讨论】:

    猜你喜欢
    • 2013-12-22
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多