如何更改ggplot2中轴标签上的小数位数? [英] How do I change the number of decimal places on axis labels in ggplot2?
问题描述
具体来说,这是在facet_grid中。已经广泛搜索类似的问题,但不清楚语法或它的去向。我想要的是Y轴上的每个数字在小数点后有两位数字,即使尾数是0。这是scale_y_continuous或element_text中的参数还是...?
row1 < - ggplot(sector_data [sector_data $ sector%in%pages [[x]],aes(date,price))+ geom_line()+
geom_hline(yintercept = 0,size = 0.3,color =gray50)+
facet_grid(〜sector)+
scale_x_date(breaks ='1 year',minor_breaks ='1 month' )+
scale_y_continuous(labels = ???)+
theme(panel.grid.major.x = element_line(size = 1.5),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_text(size = 8),
axis .ticks = element_blank()
)
从?scale_y_continuous
的帮助中,参数'labels'可以是一个函数:
升abels其中之一:
无标签
waiver()用于由转换对象计算的默认标签
提供标签的字符矢量(必须与中断长度相同)
一个将break作为输入并将标签作为输出返回的函数
我们将使用最后一个选项,该函数将 breaks
作为参数,并返回一个带有2位小数的数字。
#我们的变换函数
scaleFUN < - function(x)sprintf(%。2f,x)
#Plot
library(ggplot2)
p < - ggplot(mpg,aes(displ,cty))+ geom_point()
p < - p + facet_grid(。 〜cyl)
p + scale_y_continuous(labels = scaleFUN)
Specifically, this is in a facet_grid. Have googled extensively for similar questions but not clear on the syntax or where it goes. What I want is for every number on the y-axes to have two digits after the decimal, even if the trailing one is 0. Is this a parameter in scale_y_continuous or element_text or...?
row1 <- ggplot(sector_data[sector_data$sector %in% pages[[x]],], aes(date,price)) + geom_line() +
geom_hline(yintercept=0,size=0.3,color="gray50") +
facet_grid( ~ sector) +
scale_x_date( breaks='1 year', minor_breaks = '1 month') +
scale_y_continuous( labels = ???) +
theme(panel.grid.major.x = element_line(size=1.5),
axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_text(size=8),
axis.ticks=element_blank()
)
From the help for ?scale_y_continuous
, the argument 'labels' can be a function:
labels One of:
NULL for no labels
waiver() for the default labels computed by the transformation object
A character vector giving labels (must be same length as breaks)
A function that takes the breaks as input and returns labels as output
We will use the last option, a function that takes breaks
as an argument and returns a number with 2 decimal places.
#Our transformation function
scaleFUN <- function(x) sprintf("%.2f", x)
#Plot
library(ggplot2)
p <- ggplot(mpg, aes(displ, cty)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p + scale_y_continuous(labels=scaleFUN)
这篇关于如何更改ggplot2中轴标签上的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!