Stéphane
Stéphane

Reputation: 207

How to get rid of horizontal white lines appear out of nowhere in ggplot barplot?

enter image description here

I'm using ggplot and I get those weird horizontal lines out of geom_bar. I cannot provide a minimal working example: the same code works with few observations and it relies on data I am importing and transforming. However, I can show the relevant line of codes and cross my fingers someone ran into this issue:

ggplot(data) + geom_bar(aes(x=Horizon, y=Importance, fill=Groups),
                           position='fill', stat='identity') +
theme_timeseries2() +
scale_fill_manual(values=c('#1B9E77', 'orange2', 'black', 
                           'red2', 'blue4')) +
xlab('') + ylab('')

My personal function, theme_timeseries2() isn't the source of the problem: it happens even if I stop after geom_bar. I checked for missing values in Importance and every other column of my data frame and there are none.

It's also very odd: the white lines aren't the same on the zoomed page as in the plot window of RStudio. They do print in .png format when I save the file, so there really is something going on with those horizontal bars. Any theory about why geom_bar() does this would be highly appreciated.

Upvotes: 4

Views: 4405

Answers (3)

Emiel
Emiel

Reputation: 175

You can fix it by adding the fill as color. Like this:

geom_bar(aes(x=Horizon, y=Importance, fill=Groups, color=Groups),
                       position='fill', stat='identity')

This was suggested here.

Upvotes: 6

Y.Z.
Y.Z.

Reputation: 13

Mine went away when changing the size of the graphs in rmarkdown.

Upvotes: -1

Jon Spring
Jon Spring

Reputation: 67010

I'm guessing the lines are due to a plotting bug between observations that go into each bar. (That could be related to the OS, the graphics device, and/or how ggplot2 interacts with them...)

I expect it'd go away if you summarized before ggplot2, e.g.:

library(dplyr); 
data %>% 
  count(Horizon, Groups, wt = Importance, name = "Importance") %>% 
  ggplot() + 
  geom_col(aes(x = Horizon, y= Importance, fill = Groups), position = "fill") + ....

Upvotes: 1

Related Questions