Add axis ticks to ggplot2 - r

This is my code :
ggplot(dat,aes(x=x,y=y))
geom_point(size=5)
stat_smooth(method='glm', se = FALSE)
scale_y_log10()+ xlab("time")
ylab(expression(log(z^2)))
scale_y_continuous(breaks = round(seq(min(dat$y), max(dat$y), by = 10),1))
In the last line I wand to add ticks on y axis, but I have an error
Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.
What's wrong?

You are already doing scale_y_log10(), so adding scale_y_continuous() doesn't make sense. Instead make the breaks inside scale_y_log10():
ggplot(dat,aes(x=x,y=y)) +
geom_point(size=5) +
stat_smooth(method='glm', se = FALSE) +
scale_y_log10(breaks = round(seq(min(dat$y), max(dat$y), by = 10),1))+ xlab("time") +
ylab(expression(log(z^2)))
should work, although when you don't post a minimal example, it's hard to be sure.

Related

Change axis breaks/limits of ggplot with geom_col

I am having problems with changing the axis ticks in a barplot. I am fairly new in using ggplot so the answer might be very obvious.
Here is some data (yes it is strange, but designed to mimic the original dataset I have, which I am not allowed to share):
lab='this is just a very long example text and it will be longer and longer and longer and longer and longer and longer and longer and longer and longer and end'
number=1:20
n=unlist(lapply(number,paste,value=lab))
a=round(runif(n=20,min=-48000,max=-40000))
b=round(runif(n=20,min=-48000,max=-40000))
c=round(runif(n=20,min=-48000,max=-40000))
d=data.frame(cbind(n,a,b,c))
df=pivot_longer(d,cols=c('a','b','c'))
l1=round(as.numeric(min(df$value))/1000 )*1000+1000
l2=round(as.numeric(max(df$value))/1000 )*1000-1000
lim=seq(from=l1,to=l2,by=-1000)
colScale <- scale_fill_manual(name = "n",values = c(rainbow(nrow(df)/3)))
from which I create a barplot
p1=ggplot(df, aes(name, value, fill = as.factor(n))) +
geom_col(position = "dodge",colour='black') +
#scale_y_continuous(breaks = lim , labels = as.character(lim)) +
coord_flip() +
theme_bw() +
theme(axis.text.x=element_text(angle=90),axis.title.x=element_text(face='bold')) +
theme(axis.text.y=element_text(angle=90,size=15)) +
theme(legend.title=element_blank()) +
labs(x = "",y="test") +
colScale +
guides(fill=guide_legend(ncol=1)) +
ggtitle('something') +
theme(plot.title = element_text(hjust = 0.5,size=20))
which is this
that is basically working as I wanted, but the scaling of the x-axis is very unpleasant. What I want instead is an axis, where the breaks and labels are equal to the vector 'lim'. What I understood was that it should be possible to do this by scaling the respective axis as in the commented line. But when I'm trying this I get the error 'Discrete value supplied to continuous scale'. I tried to change the scale to 'scale_y_discrete' but then the ticks disappear completely. I tried everything I could find but nothing worked, so what is wrong?
Based on the answers I changed the plot definition to:
p1=ggplot(df, aes(name, as.numeric(value), fill = as.factor(n))) +
geom_col(position = "dodge",colour='black') +
scale_y_continuous(breaks = lim , labels = as.character(lim)) +
coord_flip() +
theme_bw() +
theme(axis.text.x=element_text(angle=90),axis.title.x=element_text(face='bold')) +
theme(axis.text.y=element_text(angle=90,size=15)) +
theme(legend.title=element_blank()) +
labs(x = "",y="test") +
colScale +
guides(fill=guide_legend(ncol=1)) +
ggtitle('something') +
theme(plot.title = element_text(hjust = 0.5,size=20))
which produced this plot
now I am able to change the axis ticks, but the plot looks nothing like the first one. My goal is to keep the look, meaning showing only the top part of the bars.
I'd suggest converting value to as.numeric (preferably before ggplot, but you can do it within, like below) and using coord_cartesian to specify the "view window". You also might find it simpler to specify your axes in the order you want them, rather than using coord_flip, which is mostly unnecessary since ggplot 3.3.0.
ggplot(df, aes(as.numeric(value), name, fill = as.factor(n))) +
geom_col(position = "dodge",colour='black') +
scale_x_continuous(breaks = lim , labels = as.character(lim)) +
coord_cartesian(xlim = c(min(as.numeric(df$value)), max(as.numeric(df$value))))
# Theming after this up to you

Problem with y axis format ( change from 1e+01)

I want to change the format of y axis from 1e+01.. to 0-200000 breaks( 0, 50000, 1000000, ...200000) in my log plot
p + geom_line(aes(group = state)) + facet_wrap(~ state)+
geom_point(aes(y = positive), col = "#8B1C62")+
scale_y_continuous(limits = c(0,200000)) + theme_minimal() +
scale_y_log10()
Also I get this error message
Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.
I don't know what to do. Thank you in advance.
Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.
This is not an error but a warning. scale_y_log is overwriting the parameters you define in scale_y_continuous.
To fix a log scale, you can use coord_trans and change the limits using ylim (untested solution)
p + geom_line(aes(group = state)) + facet_wrap(~ state)+
geom_point(aes(y = positive), col = "#8B1C62")+
theme_minimal() +
scale_y_continuous(breaks = seq(0, 200000, by = 50000)) +
coord_trans(y = “log10”, ylim = c(0,200000))
Edit: I had forgetten the question of axis ticks. You need to use breaks argument in scale_y_continous. By the way, you can directly set ylim in coord_trans (cf. the doc)

ggplot2 data labels outside margins

I'm making many figures in ggplot2 using a for loop, but my data labels are extending beyond the plot margin. I've tried using expand, but it only works for some figures. When I try to use par(mar) I get this error message:
Error: Don't know how to add o to a plot.
I also tried just using ggsave to save as a really wide file, but 1) that looks odd and 2) that won't work for making so many different figures.
Does anyone know of any other workarounds? Ideally a way to have the inner plot margins automatically set per figure based on the length of the bars + data labels. Below is the code I'm using and an example figure (you can see the bar for 'x' is outside the margin). Thank you in advance!
for (i in each) {
temp_plot = ggplot(data= subset(Data, Each == i)) +
geom_bar(stat = "identity",
aes(x = reorder(Letter, +Number), y = Number, fill = factor(Category))) +
xlab("Letters") +
ggtitle(paste0("Title"), subtitle = "Subtitle") +
coord_flip() +
theme_classic() +
theme(plot.title = element_text(hjust = 0.5, size=16),
plot.subtitle = element_text(hjust = 0.5)) +
scale_fill_manual(values = c("#00358E", "#00AFD7"),
name= "Category",
labels=c("This","That")) +
geom_text(family="Verdana", size=3,
aes(label=Number2, x=reorder(Letter, +Number), y=Number),
position=position_dodge(width=0.8), hjust=-0.001) +
scale_y_continuous(labels = comma, expand = c(0.01,0)) +
scale_x_discrete(labels = letters)
ggsave(temp_plot, file=paste0("Example", i,".jpeg"))
}
I figured out a simple solution: + ylim(0, 130000)
scale_y_continuous(expand = expansion(mult = c(0, .1)) )

How to put histogram with ggplot in the beginning of axes (0,0)?

I want to create a histogram, but I have problems with putting it in the beginning of axes (0,0). Currently it is shifted in the right which looks not good. I expected expand_limits(x = 0, y = 0) to solve this. I know it might be answered already but all solutions I've found didn't work. Thank you if you point where is the problem. Here is my code:
ggplot(data=dataset, aes(x= dataset$count)) +
geom_histogram(binwidth = 3,
col="blue",
fill="darkblue") +
labs(title="Retweets Distribution") +
labs(x="Retweet number") +
theme(plot.title = element_text(hjust = 0.5)) +
scale_x_continuous(limits = c(0,250)) +
scale_y_continuous(limits = c(0,250)) + expand_limits(x = 0, y = 0)
And the plot:
Also the summary of count column:
Plots will automatically have padding between the edge of your plot area. So even if you set the axes to start at 0, you will have space between the plot area and the margins.
As you have not provided a dataset, here is a reproducible example on how to fix it. You can change the expand option WITHIN the scale_x_continuous to remove this padding:
ggplot(diamonds, aes(carat)) +
geom_histogram() +
scale_x_continuous(expand = c(0,0))
In your case, you will have to use scale_x_continuous(limits = c(0,250), expand=c(0,0))
If you then wish to shift the whole graph left, simply alter the limits.
E.g.
scale_x_continuous(limits = c(20,250), expand=c(0,0))
See the package documentation for more details: http://ggplot2.tidyverse.org/reference/scale_continuous.html

Unexpected behaviour: italic() causing cut-off of two-line axis label in ggplot2

Use of italics (italic()) in a y-axis label that goes over two lines in ggplot is causing the first line to be partly cut off.
E.g.
ggplot() +
geom_hline(aes(yintercept = 1)) +
labs(y = expression(paste("Something\nsomething", italic(x'))))
There's no reason apparent this should be happening — the same thing doesn't happen with very similar code not using italic(), e.g. using hat() instead:
ggplot() +
geom_hline(aes(yintercept = 1)) +
labs(y = expression(paste("Something\nsomething", hat(x))))
Anyone know why this would occur or what to do about it, other than tedious manual altering plot and margin sizes or such?
Not sure why this happens but you can increase the plot margins within ggplot2...
ggplot() +
geom_hline(aes(yintercept = 1)) +
labs(y = expression(paste("Something\nsomething", hat(x)))) +
theme(plot.margin=unit(c(1,1,1,1), "cm"))

Resources