How to have separate columns for duplicate x-axis values in geom_col()?

早过忘川 提交于 2021-01-29 19:54:11

问题


I have a dataframe as below (very simple structure) and I want to draw a column chart to show the amount for each date. The issue is that the date has duplicate entries (e.g., 2020-01-15).

  # A tibble: 5 x 2
  date       amount
  <date>      <dbl>
1 2020-01-02  4000 
2 2020-01-06  2568.
3 2020-01-15  2615.
4 2020-01-15  2565 
5 2020-01-16  2640 

When I try doing the following it somehow groups the similar dates together and draws a stacked column chart which is NOT what I want.

df %>%  
    ggplot(aes(x= factor(date), y=amount)) +
    geom_col()
    scale_x_discrete( labels = df$date ) #this creates discrete x-axis labels but the values are still stacked. So it just messes things up.

There's no issue if i'm using geom_line() but I want to see a bar for each date. Any idea how to do this?


回答1:


Try:

df %>% 
  ggplot(aes(date, amount)) +
  geom_col(position = position_dodge2()) + 
  scale_x_date(breaks = unique(df$date))

Result:



来源:https://stackoverflow.com/questions/65316274/how-to-have-separate-columns-for-duplicate-x-axis-values-in-geom-col

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!