简体   繁体   中英

How to change the scale of x-y axis of graph usinig R?

I made a graph using R and this is the code. In this graph, I wanna change the scale of xy axis.

For x-axis, I want the scale unit becomes 1, not 20. Also, For y-axis, I want the scale unit becomes 100, not 500 as the graph currently has.

What codes do I need to add more in this code? Could you tell me the method?

Many thanks.

enter image description here

hist(m2$GW, xlim=c(0,100), ylim=c(0,2000), main="GW distribution (Cultivar 1)", xlab="Grain weight (mg)", ylab="Frequency (%)", col="white", las=1)

Welcome to Stack Overflow J. Kim.

You can scale your x-axis simply multiplying m2$GW by the new scale and diving it by the old scale. Following your example, if you want the x-axis to become 1, instead of 20, you simply do: m2$GW*(20/1) . To plot the histogram with a scaled x-axis you can do:

hist(m2$GW, xlim=c(0,100), ylim=c(0,2000), main="GW distribution (Cultivar 1)",
     xlab="Grain weight (mg)", ylab="Frequency (%)", col="white", las=1)

Since a histogram counts the frequency of a variable, you shouldn't change the y-axis scale, otherwise, you would lose the main information of the plot, which is the count of each x-axis' value.

If you still want to scale the y-axis, you can use ggplot2 package. Something like this may solve your problem:

library(ggplot2)
# define convenient scales for x and y
x_scale = 500/100
y_scale = 20/1
# plot
ggplot(m2) +
  geom_histogram(aes(x = GW*x_scale, y = stat(count)*y_scale),
                 fill = 'white', colour = 'black') +
  labs(title = 'GW distribution (Cultivar 1)',
       x = 'Grain weight (mg)', y = 'Frequency (%)') +
  theme(plot.title = element_text(hjust = 0.5))

I hope it helped you somehow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM