我试图使用geom_vline在ggplot2中生成的图形中添加一条垂直线,但它没有显示出来。我只想要一条垂直通过x=0的单行。以下是运行的数据和代码:
#Example data for Stack Overflow
sem <- data.frame(brand = c('com','com','com','sus','sus','sus','tol','tol','tol'),
rate = c(1,
2,
3,
1,
2,
3,
1,
2,
3),
sem = c(-100.652190547299,
-20.9635462903477,
-92.887143790098,
-32.5321197096671,
-10.8046113120258,
-103.882668200279,
39.1133320990038,
50.641868900031,
27.3390542856909))
percent_diff <- data.frame(brand = c('com','com','com','sus','sus','sus','tol','tol','tol'),
rate = c(1,
2,
3,
1,
2,
3,
1,
2,
3),
percent_diff = c(-16.8547043500825,
-123.651964249353,
-70.2307389653605,
-316.119165728843,
-290.448196586088,
-276.236250440114,
23.6027946419299,
35.415138795611,
52.9344042281165))
#Left-join the data into one data frame
library(dplyr)
df <- left_join(percent_diff, sem)
#Generate the graph
library(ggplot2)
ggplot(df, aes(x=brand, y=percent_diff, fill=factor(rate)))+
geom_bar(stat="identity",width=0.6, position="dodge", col="black")+
geom_vline(xintercept = 0)+
scale_fill_discrete(name="Rate", labels=c("1X", "2X", "3X"))+
xlab("Brand")+ylab("Percent Difference (Compared to nontreated)")+
geom_errorbar(aes(ymin= percent_diff, ymax=percent_diff+sem), width=0.2, position = position_dodge(0.6))+
ggtitle("Brand Comparison")+
scale_fill_brewer(palette='Greys', name="Rate", labels=c("1X", "2X", "3X"))+
theme(plot.title = element_text(hjust=0.5))+
coord_flip()+
geom_vline(aes(xintercept=0, col = 'red', size = 3))其结果是:

为什么出现这个输出而不是单行垂直运行?我试着加载library(scales)包,但没有得到我希望的结果。
发布于 2020-01-13 19:45:06
只需将geom_vline更改为geom_hline即可。问题是,所有的东西都是用原始的坐标和轴线绘制的。因此,您想要的行实际上是一条水平线,以后会像使用coord_flip的所有情节一样翻转。下面是我对您的代码所做的唯一修改:
#I also passed col and size outside aes
geom_hline(aes(yintercept=0),col = 'red', size = 1)

发布于 2020-01-13 19:44:46
coord_flip()可能会令人困惑。在应用coord_flip之前,您需要用原始的x和y来定义您的绘图。在本例中,这意味着使用geom_hline代替:
ggplot(df, aes(x=brand, y=percent_diff, fill=factor(rate)))+
geom_bar(stat="identity",width=0.6, position="dodge", col="black")+
geom_hline(yintercept=0, col = 'red', size = 3)

ggplot(df, aes(x=brand, y=percent_diff, fill=factor(rate)))+
geom_bar(stat="identity",width=0.6, position="dodge", col="black")+
geom_hline(yintercept=0, col = 'red', size = 3) +
coord_flip()

注意,您可以使用geom_col()而不是geom_bar(stat = 'identity')。
https://stackoverflow.com/questions/59723054
复制相似问题