I would like to create a range bar chart in R. I found a similar question that was posted about 4 years ago, but the answer was a bit awkward and cumbersome. It did the job, but I was hoping that a cleaner approach might be possible now. Using ggplot2 would be ideal.
Floating bar chart with dates as the plotted values in r
If possible, I would also like to include some sort of point data, or some other way to indicate a summary statistic, like the mean or median for that particular range.
Compared to the attached picture, the Item IDs would take the place of the months given along the y-axis and the Start and End values would be represented horizontally along the x-axis.
Although the data doesn't have to be structured this way, here is a sample dataframe to make things easier:
structure(list(Item = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20), Start = c(500, 550, 500,
450, 400, 400, 500, 400, 300, 300, 350, 250, 300, 200, 200, 100,
100, 50, 0, 0), End = c(550, 600, 550, 550, 700, 600, 600, 700,
850, 600, 650, 650, 750, 900, 800, 900, 1000, 950, 900, 1000),
Median = c(525, 575, 525, 500, 550, 500, 550, 550, 575, 450,
500, 450, 525, 550, 500, 500, 550, 500, 450, 500)), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -20L), spec = structure(list(
cols = list(Item = structure(list(), class = c("collector_double",
"collector")), Start = structure(list(), class = c("collector_double",
"collector")), End = structure(list(), class = c("collector_double",
"collector")), Median = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))```
The example picture was taken from the range bar chart entry at the "AnyChart" website.
As suggested by RAB, you can try to use geom_segment
with your dataframe df
:
library(ggplot2)
ggplot(data = df)+
geom_segment(aes(x = Item, xend = Item, y = Start, yend = End), size = 5, colour = "red", alpha = 0.6) +
geom_segment(aes(x = Item, xend = Item, y = Median-1, yend = Median+1), size = 5, colour = "black") +
coord_flip() +
scale_x_discrete(limits = as.character(ddf$Item))+
ylab("Value")
Alternatively, you can also use geom_crossbar
:
ggplot(data = ddf, aes(x = as.factor(Item), y = Median)) +
geom_crossbar(aes(ymin = Start, ymax = End), width = 0.5, fill = "grey") +
coord_flip() +
xlab("Item") +
ylab("Value")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.