grittlydev
grittlydev

Reputation: 153

ggplot2 bar graph exported to pdf is made up of segments instead of a solid shape

My problem is that when I output a ggplot bar graph as a pdf and import it in illustrator, each bar is made up of many tiny segments rather than being a single solid shape. How can I convert the bars to solid shapes either in illustrator or when exporting in R?

R code:

library("ggplot2")
data(diamonds)
gplot <- ggplot(diamonds, aes(cut,carat)) + geom_bar(stat="identity")
ggsave("gplot.pdf",gplot)

Screenshot of pdf imported into Illustrator: Screenshot Illustrator

Upvotes: 1

Views: 444

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145785

The problem is that geom_bar is using position="stack" to draw all the little bars right next to each other to stack up to the big bar. You can have it only draw one bar for each category by pre-aggregating your data:

library(dplyr)
diam = diamonds %>% group_by(cut) %>% summarize(carat = sum(carat))

g2 = ggplot(diam, aes(x = cut, y = carat)) + geom_bar(stat = "identity")
ggsave("gplot2.pdf", g2)

This also has the advantage of rendering much faster both to the PDF and if you print the plot to your graphic device.

Upvotes: 3

Related Questions