简体   繁体   中英

ggplot, bar plot by two categories

I have the following data:

> test
   ave year det
1   58 2007 det
2   61 2008 not
3   62 2009 det
4   61 2010 not
5   61 2011 det
6   61 2012 not
7   62 2013 det
8   64 2014 not
9   64 2015 det
10  60 2016 not
11  60 2017 det
12  59 2018 not
13  58 2019 det
14  60 2007 not
15  59 2008 det
16  58 2009 not
17  58 2010 det
18  57 2011 not
19  58 2012 det
20  59 2013 not
21  58 2014 det
22  56 2015 not
23  55 2016 det
24  55 2017 not
25  56 2018 det
26  55 2019 not

I want to create a bar plot using ggplot, where the ave values corresponding to level of 'det' for each year is shown. How would I do this?

Something like this?

library(ggplot2)
ggplot(df, aes(x = year, y = ave, group = det, fill = det)) + 
geom_bar(stat = 'identity', position = 'dodge')

在此处输入图片说明

You should succeed with the package ggplot2 , and the function ggplot() . If you want more informations on this package go to the "cheat sheet" of ggplot2 here : https://www.rstudio.com/resources/cheatsheets/

So you can go with something like this with your data :

ggplot(test, aes(fill=det, group=det, y=ave, x=year)) + 
    geom_bar(position="dodge", stat="identity")

Here is one fancy purpose:

library(ggplot2)
ggplot(test, aes(x = year, y = ave, group = det, fill = det, label = ave)) +
    geom_bar(stat = 'identity', position = 'dodge', width = 0.5) +
    geom_text(aes(label=ave), vjust=1.6, color="white",
              position = position_dodge(0.5), size=3.5)+
    theme_minimal()

在此处输入图片说明

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.

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