jjw
jjw

Reputation: 498

How can I add bins which has no data in bar chart using R?

my data looks like this.

   yearID teamID   salary
1    1994    LAN   109000
2    1995    LAN   114000
3    1996    LAN   124000
4    1997    LAN   270000
5    1998    LAN   700000
6    1999    LAN  2300000
7    2000    LAN  3850000
8    2001    LAN  9900000
9    2002    TEX  6884803
10   2003    TEX 13000000
11   2004    TEX 14000000
12   2005    TEX 15000000
13   2006    SDN 15505142
14   2009    PHI  2500000
15   2010    NYA  1200000


And I created a bar chart.

enter image description here

But this bar chart doesn't show 2007 and 2008 in x-axis.

Although there is no data in 2007 and 2008, I want to draw the bar chart which shows 0 in those years.

How can I create the bar chart which shows year 2007 and 2008 in x-axis?

My code is like this.

barplot(salary/1000, names.arg=yearID, las = 2,
        main = "Salary (in 1000)")

Upvotes: 1

Views: 146

Answers (2)

akrun
akrun

Reputation: 887118

One option would be to expand the dataset using the min and max of 'yearID' (assuming it is numeric) merge and then do the barplot

df2 <- merge(data.frame(yearID = min(df1$yearID):max(df1$yearID)),
      df1, all.x = TRUE)
with(df2, barplot(salary/1000, names.arg=yearID, las = 2,
      main = "Salary (in 1000)"))

enter image description here

data

df1 <- structure(list(yearID = c(1994L, 1995L, 1996L, 1997L, 1998L, 
1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2009L, 
2010L), teamID = c("LAN", "LAN", "LAN", "LAN", "LAN", "LAN", 
"LAN", "LAN", "TEX", "TEX", "TEX", "TEX", "SDN", "PHI", "NYA"
), salary = c(109000L, 114000L, 124000L, 270000L, 700000L, 2300000L, 
3850000L, 9900000L, 6884803L, 13000000L, 14000000L, 15000000L, 
15505142L, 2500000L, 1200000L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14", "15"))

Upvotes: 1

Roman
Roman

Reputation: 17648

A ggplot/tidyverse solution

library(tidyverse)
df1 %>% 
  complete(yearID =min(yearID):max(yearID), fill= list(salary=0)) %>% 
  ggplot(aes(yearID, salary/1000)) + 
   geom_col() + 
   ggtitle("Salary (in 1000)")

enter image description here

Upvotes: 0

Related Questions