如何用一条线制作一个Grouped Bar Plot

时间:2018-01-17 04:31:41

标签: r charts

我有以下数据集:

HIU,0.0833333333,0,0.35,0.0208333333,0.40625,0,0.21875,0.125,0.078125,0.0104166667,1,0.53125,0.4375
TTHY,0,0,0.8,0,0.5,0,0.7083333333,0.2708333333,0,0.6597222222,0,0.1435185185,0      
Full,0.0554986339,0.1034836066,0.4620901639,0.0683060109,0.4961577869,0.0696721311,0.222079918,0.1465163934,0.2085040984,0.0476007514,0.893613388,0.396943306,0.4223872951

我根据HIU和TTHY的行创建了一个分组条形图(图1)。但我想根据" Full"添加一行。行,例如第二张图片。

图1: Figure 1

图2: Figure 2

我怎么能用R做?这是我目前的代码:

df = read.csv('TTR-HIU/resultados.csv',header=FALSE,colClasses=c("NULL",NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA))
df.bar <- barplot(as.matrix(df[-nrow(df),]),beside=TRUE,col=c("darkblue","red"))

1 个答案:

答案 0 :(得分:1)

使用ggplot2,你可以尝试这样的事情:

# put data in data frame:
df <- data.frame(HIU = c(0.0833333333,0,0.35,0.0208333333,0.40625,0,0.21875,0.125,0.078125,0.0104166667,1,0.53125,0.4375),
                 TTHY = c(0,0,0.8,0,0.5,0,0.7083333333,0.2708333333,0,0.6597222222,0,0.1435185185,0),
                 Full= c(0.0554986339,0.1034836066,0.4620901639,0.0683060109,0.4961577869,0.0696721311,0.222079918,0.1465163934,0.2085040984,0.0476007514,0.893613388,0.396943306,0.4223872951))

library(ggplot2)
library(tidyr) # to make data long (gather)
# create x-values:
df$x <- as.factor(seq_len(nrow(df)))
# make data long for ggplot2:
df_long <- df %>% gather(key, value, -x)
ggplot() +
  # plot bars:
  geom_col(data = subset(df_long, key %in% c("HIU", "TTHY")),
           mapping = aes(x = x, y = value, fill = key),
           position = position_dodge()) +
  # plot lines:
  geom_line(data = subset(df_long, key == "Full"),
            mapping = aes(x = x, y = value, group = key, color = key),
            size = 2) +
  # make plot look a little like your desired output:
  scale_color_manual(values = c("Full" = "yellow")) +
  scale_fill_manual(values = c("HIU" = "blue", "TTHY" = "red")) +
  theme_minimal() +
  theme(axis.title = element_blank(), 
        legend.title = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank())

但是,您可能必须将数据放在数据框架形状中,如此示例所示。如果您需要进一步的帮助,请使用dput来显示您的数据的完整外观......