如何在ggplot中制作条形图?

时间:2020-07-24 19:24:06

标签: r ggplot2

我在excel中有一个文件

EXCEL FILE

我想使用ggplot软件包在R中创建与此类似的图。

Desired plot

我通过“从excel导入数据集”将此excel文件导入R

df1<-as.data.frame(GPPNPPMEAN)
> df1
  DATA MEAN  ..3
1 <NA>  GPP  NPP
2   MO 0.45  0.4
3   IP 0.21 0.25
4   MP 0.59 0.24
5   CC 0.62 0.25

我执行以下操作

ggplot(data=df1, aes(x=DATA, y=MEAN, fill=values)) +
  geom_bar(stat="identity", position=position_dodge())+
  geom_text(aes(label=len), vjust=1.6, color="white",
            position = position_dodge(0.9), size=3.5)+
  scale_fill_brewer(palette="Paired")+
  theme_minimal()

出现错误

Error: All columns in a tibble must be 1d or 2d objects:
* Column `fill` is standardGeneric
Call `rlang::last_error()` to see a backtrace

为了在gglot中进行绘制,数据帧的结构是否正确?如何在R中获得该图?

2 个答案:

答案 0 :(得分:3)

您应该像使用excel一样准备数据

enter image description here

请不要提供问题中显示的两个标题。然后另存为.csv文件中的excel文件,即可使用以下代码读取csv

df1 <- read.csv("Book1.csv", check.names = F)

df.m <- reshape2::melt(df1)

my_se <- df.m %>%
  group_by(DATA) %>%
  summarise(n=n(),
            sd=sd(value),
            se=sd/sqrt(n))

df.m %>% 
  left_join(my_se) %>% 
  ggplot(aes(x = DATA, y = value, fill = variable)) + 
  geom_bar(stat="identity", position = "dodge")+
  geom_errorbar(aes(x=DATA, ymin=value-se, ymax=value+se), width=0.4, position = position_dodge(.9))+
  theme_minimal()

enter image description here

答案 1 :(得分:2)

ggplot(data=df2, aes(x=dose, y=len, fill=supp)) +
geom_bar(stat="identity", position=position_dodge())+
  geom_text(aes(label=len), vjust=1.6, color="white",
            position = position_dodge(0.9), size=3.5)+
  scale_fill_brewer(palette="Paired")+
  theme_minimal()

该代码可帮助您创建以下条形图。您可以根据需要更改值