I am trying to create 4 bar plots that simply present number of responses split by various demographics.
Thus I have the following chunk of code
{r, echo = FALSE, fig.height=20, fig.width=40} <-this is has the proper start but stackoverflow wont let me post it
a <- ggplot(data=Data, aes(x=Gender, fill=Gender))+
geom_bar(stat="count")+
scale_x_discrete(labels = wrap_format(10))+
ylab("Number of respondents")
b <- ggplot(data=Data, aes(x=Condition, fill=Condition))+
geom_bar(stat="count")+
scale_x_discrete(labels = wrap_format(10))+
ylab("Number of respondents")+
xlab("Employment type")
c <- ggplot(data=Data, aes(x=Schedule, fill=Schedule))+
geom_bar(stat="count")+
scale_x_discrete(labels = wrap_format(10))+
ylab("Number of respondents")
d <- ggplot(data=Data, aes(x=Region, fill=Region))+
geom_bar(stat="count")+
scale_x_discrete(labels = wrap_format(10))+
ylab("Number of respondents")
plot_grid(a,b,c,d)
This presents the plots in a nice grid. However the graphs are unreadably small unless one zooms in a lot.
However, messing with the fig.height and fig.width either make the graphs incredibly tiny or larger but then all the data in each graph is so squashed.
How can one simply resize the graph appropriately while maintaining readability?
Related
I want to display two plots (ggplot) side-by-side in an html report. Most resources suggest grid.arrange() from the package gridExtra is the simplest way to accomplish this. However, grid.arrange() is changing the proportions of my plots (squishing them along the x-axis). I want to maintain axis proportions. I've played with widths= and heights= options but nothing has worked.
If this isn't easily resolved with grid.arrange(), are there other alternatives for displaying images side-by-side?
P.S. I did see altering height of rows produced by grid.arrange when nrow=1, but the solution did not work for me.
Thanks!
{r Images, echo=FALSE}
p1 <- ggplot(pcaData, aes(PC1, PC2, color=By_Experiment, shape=Date)) +
geom_point(size=3) +
xlab(paste0("PC1: ",percentVar[1],"% Variance")) +
ylab(paste0("PC2: ",percentVar[2],"% Variance")) +
labs(title="PCA of Gene Counts (rLog Transformed)") +
theme(axis.line = element_line(color = "black"))
p2 <- ggplot(pcaData, aes(PC1, PC2, color=By_Experiment, shape=Calcium_TP)) +
geom_point(size=3) +
xlab(paste0("PC1: ",percentVar[1],"% Variance")) +
ylab(paste0("PC2: ",percentVar[2],"% Variance")) +
labs(title="PCA of Gene Counts (rLog Transformed)") +
theme(axis.line = element_line(color = "black"))
p1
p2
grid.arrange(p1, p2, ncol=2)
You can control the dimensions of the plots produced in an HTML report by including fig.width and fig.height in the beginning of the code chunk. Try to include {r, fig.width=12, fig.height=4} and see if the plots looks less squashed.
I have done a barplot in RStudio successfully, but I want to decrease the space between the categories (CPLEX and Heurística), but I can't do it. My objective is to make this figures thinner since I am working in a latex file where I want to put two of this plots side by side in the same line, but they are too wide and the get out of the margins. My code is the following.
library("ggplot2")
df <- data.frame(
Metodo = factor(c("CPLEX","Heurística"),levels=c("CPLEX","Heurística")),
Item = factor(c("Demanda total","UE","UI")),
Unidades = c(6440,6291,0,6440,6440,149)
)
ggplot(data=df, aes(x=Metodo, y=Unidades, fill=Item)) +
geom_bar(stat="identity", position=position_dodge(), colour="black",width=0.3) +
theme(text = element_text(family="serif", size=12,face="bold")) +
labs(x = "Método") +
ggtitle("Instancia 1") +
theme(legend.position="top")
ggsave("I1.png")
And the output is
I would like to reduce the wide of this plot, obviously without deforming it. Any ideas?
Add width into position_dodge:
ggplot(data=df, aes(x=Metodo, y=Unidades, fill=Item)) +
geom_bar(stat="identity", position=position_dodge(width = 0.5), colour="black",width=0.3) +
theme(text=element_text(family="serif", size=12,face="bold"))+labs(x="Método")+ggtitle("Instancia 1")+theme(legend.position="top")
I'd like to create a markdown document out of my R script. I managed it to display different barplots, piecharts, a leaflet map and so on.
But it doesn't work with ggplot.
{r, eval=TRUE, echo=TRUE, warning=FALSE, message=FALSE}
p <- qplot() +
theme_classic() +
ggtitle("Title") +
coord_fixed(ratio = 1) +
xlab("wrong") +
ylab("super") +
geom_polygon(data=fortify(data1),
aes(x=long, y=lat, group=group), alpha=0.1, fill=NA, col="black", size=0.1) +
geom_point(data = as.data.frame(data2),
aes(x = coords.x1, y = coords.x2, color = pal1), shape=4, alpha=1)
p + theme(legend.position="right")
The plot looks totally fine if i export it with ggsave, but in the markdown the x axis is pressed together.
Without a reproducible example, it is difficult to work out your problems. However, you could try to change a few lines (each at a time) to see if it makes a difference. Particularly, I would remove the line coord_fixed(ratio = 1) + to see what happens. You could also try different ratio numbers as well to get what you want.
If this does not fix your problem, please provide a reproducible example data.
I am having trouble with excessively wide panel labels on my ggplot2 faceted plot.
Here is the code that I used to generate the plot:
png(paste("/directory/", hgnc_symbol, "_", curr_gene, ".png", sep=""),
width=4, height=3, units="in", pointsize=1, res=300)
print({barplot <-
ggplot(curr_data, aes(x = condition, y = tpm, fill=condition)) +
geom_boxplot(outlier.colour=NA, lwd=0.2, color="grey18") +
stat_boxplot(geom ='errorbar', color="grey18") +
geom_jitter(size=0.8) +
facet_wrap(~target_id) +
guides(fill=FALSE) +
theme_bw() +
labs(title=paste(hgnc_symbol, "_", curr_gene, sep="")) +
labs(x="condition") + labs(y="TPM") +
theme(text = element_text(size=5), strip.background=element_rect(size = 1),
axis.text.x = element_text(angle = 90, hjust = 1, size=4.5))})
dev.off()
The plot comes out looking like this:
As you can see, the background of the panel labels is so wide, that the plots themselves are barely visible. The points plotted on the graph are also much larger than I expected them to be.
The odd thing is that I used this same exact code to produce this following plot (which looks good) just a few days ago:
What is causing this difference, and how can I fix the problem?
In ggplot, text is defined in pts, which are absolute units of measure. The plot panel is relative in size and scales according to the dimensions you specify when you save your plot. If the dimensions are small, then the text will be large relative to the panel areas. If the dimensions are large, then the text will be small relative to the panel areas. See examples below:
ggplot(diamonds, aes(x = x, y =y)) + geom_point() + facet_wrap(~ clarity)
ggsave("filepath//4x3.png", width=4, height = 3)
ggsave("filepath//8x6.png", width=8, height = 6)
The 4 x 3 in plot:
The 8 x 6 in plot:
You can edit the grobs to exert finer control on the plot dimensions (example).
I'd like to add a footnote citation to my 3-panel facet grid plot produced in R. It's a footnote to credit the data source. I'd ideally like to have it below and external to all three axes---preferably in the lower left.
I'm using ggplot2 and also ggsave(). This means I can't use grid.text()-based solutions, because that only draws on the x11() window, and can't be added to the ggplot object.
Using instead png() ...code... dev.off() does not appear to be an option because I need ggsave's resizing parameters, and find this command produces better, clearer prints (that are also much faster, because I'm not printing to the screen).
Here's my basic code:
p1 <- ggplot(data, aes(date, value))
facet_grid(variable ~ .) + geom_point(aes(y =value), size=1) +
theme_bw() +
opts(title=mytitle)
print(p1)
ggsave("FILE.png",width=mywidth, height=myheight, p1, dpi=90)
I've tried:
p1 <- ggplot(data, aes(date, value))
facet_grid(variable ~ .) + geom_point(aes(y =value), size=1) +
theme_bw() +
opts(title=mytitle)
print(p1)
grid.text(unit(0.1,"npc"),0.025,label = "Data courtesy of Me")
grid.gedit("GRID.text", gp=gpar(fontsize=7))
ggsave("FILE.png",width=mywidth, height=myheight, p1, dpi=90)
This appropriately puts the footnote in the lower left corner on the x11() display, external to the plots, but unfortunately, since it isn't applied to the p1 object, it isn't saved by the ggsave command.
I've also tried:
p1 <- ggplot(data, aes(date, value))
facet_grid(variable ~ .) + geom_point(aes(y =value), size=1) +
theme_bw() +
opts(title=mytitle) +
annotate("text", label = "Footnote", x = 0, y = 10, size = 5, colour = "black") +
print(p1)
ggsave("FILE.png",width=mywidth, height=myheight, p1, dpi=90)
This successfully prints using ggsave, however it has the following problems:
It is repeated 3 times, in each of the 3 facets, rather than 1 time.
It is contained within the plots, rather than external to them.
Text is difficult to place---seems to be using plot units (my x-axis is date, so 0 puts it around 1970).
The text size doesn't seem to change despite my size parameter.
A couple of related links from when I explored this...
ggplot2 footnote
(doesn't work with ggsave)
How to label the barplot in ggplot with the labels in another test result?
(is inside the plot, not external/below plot)
Different font faces and sizes within label text entries in ggplot2
(doesn't work with ggsave)
problem saving pdf file in R with ggplot2
ggplot2 now has this ability natively with no need for additional packages. ... + labs(caption = "footnote", ...)
library(ggplot2)
ggplot(diamonds, aes(carat, price, color = clarity)) +
geom_point() +
labs(title = "Diamonds are forever...",
subtitle = "Carat weight by Price",
caption = "H. Wickham. ggplot2: Elegant Graphics for Data Analysis Springer-Verlag New York, 2009.")
library(gridExtra)
library(grid)
library(ggplot2)
g <- grid.arrange(qplot(1:10, 1:10, colour=1:10) + labs(caption="ggplot2 caption"),
bottom = textGrob("grid caption", x = 1,
hjust = 1, gp = gpar(fontface = 3L, fontsize = 9)))
ggsave("plot.pdf", g)
Edit: note that this solution is somewhat complementary to the recent caption argument added to ggplot2, since the textGrob can here be aligned with respect to the whole figure, not just the plot panel.
Adding to the answer of Brandon Bertelsen: if you want to have the caption in the left corner, add
theme(plot.caption = element_text(hjust = 0))