简体   繁体   English

如何在条形图中绘制垂直线?

[英]How to draw vertical lines in barplot?

I want to draw a vertical line at specific positions of the x-axis, but the x-positions of the lines aren't correct.我想在 x 轴的特定位置画一条垂直线,但线的 x 位置不正确。 How can I solve this ?我该如何解决这个问题?

x <- c(0,0,0,4,5,6)
barplot(x, names.arg=1:length(x))
abline(v=1:length(x), col="red")
abline(v=c(5.5), col="blue")

You have to save the result of barplot .您必须保存barplot的结果。 Then use those values to plot the vertical lines.然后使用这些值绘制垂直线。

x <- c(0,0,0,4,5,6)
bp <- barplot(x, names.arg = seq_along(x))
abline(v = bp, col = "red")
abline(v = 5.5, col = "blue")

在此处输入图片说明

Note that the blue line was plotted twice and therefore became violet.请注意,线绘制了两次,因此变成了紫色。 So remove the value 5.5 from the first call to `abline所以从第一次调用 `abline 中删除值5.5

bp <- barplot(x, names.arg = seq_along(x))
abline(v = bp[bp != 5.5], col = "red")
abline(v = 5.5, col = "blue")

在此处输入图片说明

If you don't have to stick to base plot , you can do the same using ggplot2 and geom_vline function:如果您不必坚持使用base plot ,则可以使用ggplot2geom_vline函数执行相同操作:

library(ggplot2)
x <- c(0,0,0,4,5,6)
d <- data.frame(x)
ggplot(d, aes(x = seq(1:6), y = x))+
  geom_bar(stat = "identity")+
  scale_x_continuous(breaks = 1:6)+
  geom_vline(xintercept = 1:6, color = "red")+
  geom_vline(xintercept = 5.5, color = "blue")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM