Line graph is blurry, not clear & axes positioning difficulties in R - r

I am trying to plot (with ggplot2) a simple time-velocity graph in R, but my data looks messy. I am using Markdown Notebook.
I am using this base code for this:
ggplot(data, aes(x = time, y = velocity)) + geom_line() +
scale_x_continuous(name="Time (s)",
limits=c(min(data$time),max(data$time)),breaks=seq(0,3000,500)) +
scale_y_continuous(name="", limits=c(-1,max(data$velocity))) +
theme(axis.text = element_text(color="black"),axis.title = element_text(
color="black"))
This is how it looks like with the default settings:
After that, I tried to extend the figure horizontally, but then the labels became really small, and the data is still kind of blurry:
For this, I added the following (at the beginning of my Chunk):
{r fig1, fig.width=95, fig.asp = 0.15}
If I make the font sizes bigger the labels look okay, but the velocity graph stays the same (naturally). Does someone know a way to fix that? I thought that maybe this is because of my monitor, it has 4K resolution, but I'm not sure. I also wonder if anyone knows how to move the y-axis so it would start at the zero point of the x-axes (now there's a space, and it looks weird).
I am also open to suggestions on how to improve the visualization. :D Thank you in advance!
with the changed DPI (comment) it looks better in my opinion, but the figure is really small (I included the output window for reference):

Related

Save plot exactly as previewed in the "Plots" panel

I know that a very similar question already exists here, but the provided answer did not work for me.
This is my usual workflow: I generate a plot and adjust the size of the plot in the "Plots" Panel of RStudio until I am satisfied. I then call dev.size() to get the exact size.
Afterwards, I save the plot with ggsave(...,dpi=300) and specify the previously determined width and height. The problem is, that after saving, the plot looks completely different, especially the text sizes.
If I use the "Export" option from RStudio the plot looks exactly as it does in the preview, but the quality is quite bad and doing this manually is tedious.
Here is the picture, that hopefully illustrates what I mean:
The code I use to save the plot looks like this:
library(ggplot2)
ggplot(mtcars, aes(x = mpg, y = wt)) +
geom_point() +
facet_grid(vs + am ~ gear, margins = "vs") +
theme_Publication()
ggsave("plot.png", width=4, height=3.2, dpi=300)
I would love to know, if there is an option to "programmatically" save a plot which exactly recreates the "Plots" preview in high quality.
Thanks a lot in advance!

Map cut on the "edges" of x-axis with Aitoff projection

I am trying to plot with ggplot2 (v3.3.2) data points on a map using a specific projection (called aitoff), which is useful especially for sky plots.
When doing so, the plot is "cropped" on the x-axis, i.e. the edges of the axis are located just outside the plot. I tried a few things (adjust the margin for example), but without success. Could you please help to make these part of the plot visible?
Here is the code to reproduce the issue, i.e. the point located at (0,0) is not visible.
skydata <- data.frame(RA=c(0,180,360), Dec=c(0,10,20))
ggplot(skydata) +
geom_point(aes(RA,Dec)) +
coord_map(projection="aitoff",orientation=c(90,180,0)) +
scale_y_continuous(breaks=(-2:2)*30,limits=c(-90,90)) +
scale_x_continuous(breaks=(0:8)*45,limits=c(0,360), labels=c("","","","","","","","","")) +
labs(x="R.A.(°)", y="Decl. (°)",title="Map of the sky")
I hope I was clear enough...
Thanks a lot!
I think that the clipping happens in the first place is a known issue. In the Github issue hadley says: "I think this is a long standing problem that I'm unlikely to solve in the near future"
I think there are two ways, you can more or less solve the problem for yourself. One solution was already mentioned by #Arnaud
(but both solutions have downsides)
Add clip = "off" in the coord_map part
Add expand = c(1.1,0) in the scale_x_continuous part
I added you some example plots, where you can see the results and problems.
1. Initial version (if I run your code):
Problem: The point at (0,0) can't be seen properly.
2. Version with expand:
skydata <- data.frame(RA=c(0,180,360), Dec=c(0,10,20))
ggplot(skydata) +
geom_point(aes(RA,Dec)) +
coord_map(projection="aitoff", orientation=c(90,180,0)) +
scale_y_continuous(breaks=(-2:2)*30,limits=c(-90,90)) +
scale_x_continuous(breaks=(0:8)*45,limits=c(0,360), ,expand = c(1.1, 0), labels=c("","","","","","","","","")) +
labs(x="R.A.(°)", y="Decl. (°)",title="Map of the sky")
Looks quite nice now. x-axis got expanded to both sides, point in (0,0) now clearly visible.
But attention seems to work only with natural numbers (like expand = c(5,0)). For the 1.1 I chose in my example the plot is somehow different and the y-axis seems distorted.
3. Version with clip = "off":
skydata <- data.frame(RA=c(0,180,360), Dec=c(0,10,20))
ggplot(skydata) +
geom_point(aes(RA,Dec)) +
coord_map(projection="aitoff", clip = "off", orientation=c(90,180,0)) +
scale_y_continuous(breaks=(-2:2)*30,limits=c(-90,90)) +
scale_x_continuous(breaks=(0:8)*45,limits=c(0,360), labels=c("","","","","","","","","")) +
labs(x="R.A.(°)", y="Decl. (°)",title="Map of the sky")
This version does not expand the x-axis, but it makes sure, the point at (0,0) is not clipped off. Definitely no distortion of the y-axis. But does not look as good as the solution with expand.

How to make the bg of a single legend transparent in a merged plot?

I don't have to mention I am new, and my problem has too many solutions. I tried about 12 different versions and couldn't solve it:
The example given is close to my desired plot I want to generate.
I overtook a given script from 2013, so I do not entirely understand what to do to change it in the way I would like:
Plot 1's legend in the bottom right corner without a title, transparent background and instead of 1 and 2 the labels "urban" and "non-urban".I am aware that "legend.position="none"" delets all legends, but was not able to find a solution that looked like at least close to this. Still it is not on the plot, not transparent and has a title.
Unfortunately somehow the dots changed into squares in this process and I have no clue why. I didn't change geom_point.
Another flaw I want to change is to remove the top line over the central plot. But how?
And last but not least I am not sure if the function geom.mooth(method=lm) does reflect the regression line + confidence interval, because the description says it adds a conditional mean which is, afaIk, not the same. Is my concern unnecessary?
Edit: shorter Version plot1 out of 3 merged plots:
library(ggplot2)
library(gridExtra)
set.seed(42)
DF <- data.frame(x=rnorm(100,mean=c(1,5)),y=rlnorm(100,meanlog=c(8,6)),group=1:2)
p1 <- ggplot(DF,aes(x=x,y=y,colour=factor(group))) + geom_point(shape=16) +
scale_x_continuous(expand=c(0.02,0)) +
scale_y_continuous(expand=c(0.02,0)) +
geom_rug() +
geom_smooth(method=lm,alpha=0.3) +
theme_bw()+
theme(legend.position=c(0.9,0.09),
legend.title=element_blank(),
plot.margin=unit(c(0,0,0,0),
"points"))
Thanks for any advice, I am researching on this topic since 2 weeks, even though I thought I am studying psychology, I learned a lot ... but not enough in the short time to success. :/

Oddly shaped markers in ggplot2

I recently installed ggplot2 and tried a qplot. The plot comes out like this,
If you notice you can see that the markers seem to look deformed rather than circles. Is there a way to correct this?
Here is my code:
require(ggplot2)
set.seed(1410)
qplot(carat, price, data = diamonds)
EDIT: The plot looks fine when exported to a pdf.
I am using R3.0.2 ggplot2_0.9.3.1 on elementary OS.Thanks.
I usually don't worry about the look of the picture in the "window view" / "r view" -- it is just a graphical view of what the picture will look given the current setting for the resolution.
If possible, I save a picture as an eps or pdf file. They are vector based picture and scale well regardless of size.
If I don't use an eps or pdf file, I use png files to save my pictures:
g1 <- ggplot(data, aes(x=X1, y=Y1)+
geom_point(x)
png("high_res_png.png", width = 10000, height = 7000, res = 1300)
print(g1)
dev.off()
Using a lot of pixels on a png will prevent the "saved" picture from looking "fuzzy" or "oddly" shaped (the size of it will be large, but the png looks good even when you zoom in). Hope that helps.
The goofy looking circles is an artifact of your window system; on my Mac OS X (Quartz) setup, default qplot gives great-looking circles. However, I recall that the points do look a little like yours on my Linux box at home...
Shape is customizable, though. The following gives squares rotated 45 degrees, for instance:
qplot(carat, price, data = diamonds) + scale_shape_identity() + geom_point(shape = 23)

panel.border in ggplot2 ploting thicker lines in bottom and right side of the plot in CairoPDF device

I am using Cairo setting as
CairoPDF(file = "test2.pdf", width = 8.3, height = 11.7)
and theme setting is like this:
mytheme<-theme_bw() +
theme(plot.title = element_text(lineheight=.8, face="bold"),
text=element_text(size=11, family="Times New Roman"))+
theme(panel.border = element_rect(linetype = "dashed",
colour = "black"))+
theme(plot.margin = unit(c(1,1.5,1,1.5), "inches"))
I guess, this is a problem with my theme setting for ggplot. please give advice to fix it.
Thanks.
Using only theme_bw() I can reproduce the feature.
df <- data.frame(lab = c('D1','D2','D3'),y = c(4,8,10),x= c(1,2,3))
library(Cairo)
#CairoPDF(file = "test2.pdf", width = 8.3, height = 11.7)
library(grid)
library(ggplot2)
ggplot(df, aes(xmin = x-0.2, xmax = x + 0.2, ymin = 0, ymax = y,fill=lab)) +
geom_rect()+xlim(labels = as.character(df$lab))+ theme_bw()
dev.off()
It seems that the combination of Cairo and ggplot2, when we use a theme, creates some rendering problems.
One workaround is to save in simple pdf. I hope that others give a better solution using this reproducible example.
pdf(file = "test2.pdf", width = 8.3, height = 11.7)
This may or may not fix your specific problem, but I often have this issue with 'grid' objects with respect to the pixel scaling. I can frequently fix the problem by slightly reducing or increasing the size of the image.
I would troubleshoot by taking the following steps:
Print the object to a screen plotting device, and see if the problem is still there. If not, the problem exists between your plotting device (in memory) and the exporter (CairoPDF). In that case, print to the screen first, and then save the file. Make sure the screen plotting device has the appropriate size.
Try adjusting the size of the 'width' and 'height' arguments. If you see the problem changing or others popping up, then you have a problem with scaling between the size of the plotting device and the export file. Make sure you get a pixel-exact match between the two, by using the format of: windows(width=8.3, height=11.7, xpinch=72, ypinch=72) before you print the plot to screen.
Test exporting directly to a different format. It may be that the problem is only in the specific exporter. If you can print directly to a PNG file without a problem, then the issue is probably with the way the CairoPDF exporter is working. You may find it easier to simply use the other file format or to manually convert the PNG (or other file) into a PDF using a different program, like LibreOffice or ImageMagick.
Good luck!
I have the same problem with bottom and right panel borders becoming thicker when sending the above ggplot example code to svg, pdf, cairo_pdf etc.
Here's a workaround that I use in Inkscape which might give some insight to someone with better understanding of R and pdf/svg rendering:
In Inkscape:
select the panel border
object > ungroup (do this twice)
or keyboard shortcut shift+ctrl+G (x2)
So it seems the panel border is grouped with the panel background. Surprisingly rather than the bottom and right becoming thinner, the top and left become thicker. So actually it looks like OP question should be rephrased to "plotting thinner lines in top and left side of plot".

Resources