Apologies if this has been asked before, but it is difficult to articulate in order to find an answer.
I have the following set of data below. In R, I would like to construct a bar plot for PV1
and PV2
for AvgRead
and AvgUniq
. For the error bars, I would like to set MinRead
and MinUniq
as the minima, and MaxRead
and MaxUniq
as the maxima.
If you could help that would be greatly appreciated. Again my apologies if this has been asked before.
AvgRead MinRead MaxRead AvgUniq MinUniq MaxUniq
PV1 20 10 40 40 20 80
PV2 40 20 80 80 40 160
You need to reshape your data a little bit using the melt()
and dcast()
functions from reshape2
:
library(reshape2)
library(ggplot2)
df <- data.frame(
row.names = c("PV1", "PV2"),
AvgRead = c(20, 40),
MinRead = c(10, 20),
MaxRead = c(40, 80),
AvgUniq = c(40, 80),
MinUniq = c(20, 40),
MaxUniq = c(70, 160)
)
df$name <- row.names(df)
df_molten <- melt(df)
df_molten$var1 <- substr(df_molten$variable, 1, 3)
df_molten$var2 <- substr(df_molten$variable, 4, 10000)
df_cast <- dcast(df_molten, name + var2 ~ var1, value.var = "value")
ggplot(data = df_cast, aes(x = name, y = Avg, fill = var2)) +
geom_bar(stat = "identity", position = "dodge") +
geom_errorbar(
aes(ymin = Min, ymax = Max),
width = 0.5,
size = 1.3,
position = position_dodge(0.9)
)
EDIT: to change the order of the bars you need to change var2 to factors and sort the levels accordingly:
df_cast <- dcast(df_molten, name + var2 ~ var1, value.var = "value")
df_cast$var2 <- factor(df_cast$var2, levels = c("Uniq", "Read"))
ggplot(data = df_cast, aes(x = name, y = Avg, fill = var2)) +
geom_bar(stat = "identity", position = "dodge") +
geom_errorbar(
aes(ymin = Min, ymax = Max),
width = 0.5,
size = 1.3,
position = position_dodge(0.9)
)
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.