Reputation: 17
I am new to R and today I try to save my figure by following the code:
powerplant <- ggplot(Emission.l, aes(x = Year, y = value, fill = variable))+
theme(axis.text.x = element_text(angle = 90, hjust = 1))+
geom_bar(stat = 'identity', position = 'dodge') +
ggtitle(Emission.Aerosol$Facility.Name)+
ylab("Emission(Tons)")+scale_fill_discrete(name = '', labels = c('SO2 (tons)', 'NOx (tons)')) +
scale_x_continuous(breaks = 2003:2015)
png(file = paste0(Emission.Aerosol$Facility.Name,".png"),
width = 439, height = 266, units = "px",pointsize = 12,
bg = "transparent")
dev.off()
Then, I can see the png file was created in my folder but it was only a white figure. Please let me know what is wrong with my code. Thanks a lot!
Upvotes: 0
Views: 255
Reputation: 8666
In general, I personally find it is cleaner to separate out the construction of ggplot()'s as detailed below, this makes it easier to play with the construction of the ggplot as you build the plot grammar, then you can choose how you save / print it.
I hope this helps.
require(ggplot2)
gp <- ggplot(Emission.l, aes(x = Year, y = value, fill = variable))
gp <- gp + theme(axis.text.x = element_text(angle = 90, hjust = 1))
gp <- gp + geom_bar(stat = 'identity', position = 'dodge')
gp <- gp + ggtitle(Emission.Aerosol$Facility.Name)
gp <- gp + ylab("Emission(Tons)")
gp <- gp + scale_fill_discrete( name = '',
labels = c('SO2 (tons)', 'NOx (tons)'))
gp <- gp + scale_x_continuous(breaks = 2003:2015)
powerplant <- gp
print(powerplant)
dev.off()
Upvotes: 0
Reputation: 173537
Try,
png(...)
print(powerplant)
dev.off()
or just use ggsave
. The png
command doesn't actually put any plots on disk. It simply creates a blank png file that is then ready to receive a plot. After you run it, you send ggplot
or lattice
graphics to the device by print
ing them. Base graphics commands will be sent directly to the device.
Upvotes: 2