Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:GGPlot中具有两个独立类别的堆叠垂直条形图_R_Ggplot2 - Fatal编程技术网

R:GGPlot中具有两个独立类别的堆叠垂直条形图

R:GGPlot中具有两个独立类别的堆叠垂直条形图,r,ggplot2,R,Ggplot2,我试图生成一个堆叠的垂直条形图,但我不确定如何重塑数据集以满足ggplot的期望 我有一个数据框,它有两列,“killed”和“injust”,每列都与一个州名关联。我想要一个竖直的条形图,每个州的“受伤人数”叠加在“死亡人数”之上 我可以生成这样的标准条形图: ggplot(data=data, aes(x=state,y=killed)) + geom_bar(position="dodge",stat="identity") + coord_flip() + ggtitle

我试图生成一个堆叠的垂直条形图,但我不确定如何重塑数据集以满足ggplot的期望

我有一个数据框,它有两列,“killed”和“injust”,每列都与一个州名关联。我想要一个竖直的条形图,每个州的“受伤人数”叠加在“死亡人数”之上

我可以生成这样的标准条形图:

ggplot(data=data, aes(x=state,y=killed)) + 
  geom_bar(position="dodge",stat="identity") + 
  coord_flip() +
  ggtitle("Mass Shooting Killings and Injuries") + 
  labs(x="Killings and Injuries", y="State") +
  ggtitle("Victims")
我知道“堆叠”条形图的方法是向ggplot美学添加填充组件,但问题是我不确定如何以适合我的数据的方式这样做

假再现示例:

data <- read.table(text = "state killed injured 
1 Arkansas 23 50 
2 Alabama 10 20
3 Texas 19 18
4 Ohio 14 15
5 Illinois 3 5", sep = "", header=T)

library(ggplot2)
library(reshape)
ggplot(data=data, aes(x=state,y=killed)) + 
  geom_bar(position="dodge",stat="identity") + 
  coord_flip() +
  ggtitle("Mass Shooting Killings and Injuries") + 
  labs(x="Killings and Injuries", y="State") +
  ggtitle("Victims")

data我必须使用
melt
重新塑造data.frame,以获得此图:

temp <- melt(data, id="state")
ggplot(data=temp, aes(x=state,y=value, fill=variable)) + 
  geom_bar(position="stack",stat="identity") + 
  coord_flip() +
  ggtitle("Mass Shooting Killings and Injuries") + 
  labs(x="Killings and Injuries", y="State") +
  ggtitle("Victims")

temp我必须使用
melt
重新塑造data.frame以获得此图:

temp <- melt(data, id="state")
ggplot(data=temp, aes(x=state,y=value, fill=variable)) + 
  geom_bar(position="stack",stat="identity") + 
  coord_flip() +
  ggtitle("Mass Shooting Killings and Injuries") + 
  labs(x="Killings and Injuries", y="State") +
  ggtitle("Victims")

temp您能提供一个数据帧的示例吗?刚刚添加了一个。这些数据是专有的,所以我只是做了些修改。你能提供你的数据框架的样本吗?只是添加了一个。这些数据是专有的,所以我刚刚做了一件事——upMelt是关键——notedMelt是关键——noted