我在R中使用ggplot创建了两个图形但是考虑将它们组合起来,释放的能量和原始图形都绘制在Y上。这个条形布局类似只在excel中创建但是组作为我的x(顶部)。
ggplot(data=biodiesel, aes(x=ï..Group, y=Energy..J.g., fill=Oil)) +
geom_bar(stat="identity")+
theme(legend.title=element_blank()) +
theme(panel.grid.major = element_blank()) +
theme(panel.grid.minor = element_blank())+
theme(legend.justification = c(1, 1), legend.position = c(0.25, 1))+
theme(legend.background = element_blank(),legend.key = element_blank())+
ylab("Energy Released (J/g)")+
xlab("Group Number")
ggplot(data=biodiesel, aes(x=ï..Group, y=Original..J.g., fill=Oil)) +
geom_bar(stat="identity",position="dodge" )+
theme(legend.title=element_blank()) +
theme(panel.grid.major = element_blank()) +
theme(panel.grid.minor = element_blank())+
theme(legend.justification = c(1, 1), legend.position = c(1, 1))+
theme(legend.background = element_blank(),legend.key = element_blank())+
ylab("Original Energy of Oil (J/g)")+
xlab("Group Number")
数据:
Group Oil Energy (J/g) Original (J/g)
11 Olive 2600 37000
8 Sunflower 2510.4 34040
9 Avocado 1888.2 40600
1 Rice Bran 1549 37000
2 rapeseed 1255.04 33930
7 olive 1004.16 37000
4 Sesame 1003.2 37,000
5 corn 627 34080
3 rapeseed 501.6 33930
6 olive 314 37000
10 Methanol 278.93 22000
要获得与第一个图表相同的情节,您需要使用biodiesel
制作表格gather
。你可以使用position = "dodge2"
,但是这些酒吧彼此相邻而不是彼此重叠。唯一的问题是油菜籽和橄榄油在你的数据中是两倍,所以这看起来有点奇怪!
biodiesel %>%
# make wide
gather(Energy, value, -Group, -Oil) %>%
ggplot(aes(x = Oil,
y = value,
fill = Energy)) +
geom_bar(stat = "identity",
position = "dodge2")
请务必以可直接读取的形式发布数据,例如:
library(ggplot2)
dt<-read.table(text="
Group Oil Energy Original
11 Olive 2600 37000
8 Sunflower 2510.4 34040
9 Avocado 1888.2 40600
1 Rice_Bran 1549 37000
2 rapeseed 1255.04 33930
7 olive 1004.16 37000
4 Sesame 1003.2 37000
5 corn 627 34080
3 rapeseed 501.6 33930
6 olive 314 37000
10 Methanol 278.93 22000 ",header=T)
你可能需要摆弄position
和width
以及传说中的理由
ggplot(data=dt, aes(fill=Oil)) +
geom_bar(mapping = aes(x = Group, y = Original), position=position_nudge(x = 0.2), width=0.2,stat = "identity",color="green" ) +
geom_bar(mapping = aes(x = Group, y = Energy*5), position=position_nudge(x = -0.2), width=.2, stat = "identity", color = "blue") +
scale_y_continuous(name = "Original Energy of Oil (J/g)",
sec.axis = sec_axis(~./5, name = "Energy Released (J/g)"))+
theme(
axis.title.y = element_text(color = "grey"),
axis.title.y.right = element_text(color = "blue"))+
theme(legend.justification = c(3, 1), legend.position = c(0.25, 1))+
theme(legend.background = element_blank(),legend.key = element_blank())+
xlab("Group Number")
这类似于Plot with 2 y axes, one y axis on the left, and another y axis on the right