ggplot2作图:使用对数坐标轴

如题所述

参考《R数据可视化手册》

一、默认

library(ggplot2)

library(MASS) # Load MASS for the Animals data set

animals_plot <- ggplot(Animals, aes(x = body, y = brain, label = rownames(Animals))) +

geom_text(size = 3)

animals_plot

发现由于数据在左上角和右下角都有个别分布,导致在坐标轴原点附近数据大量集中。

二、方法1:使用对数坐标轴

animals_plot +

scale_x_log10() +

scale_y_log10()

坐标轴进行变换后,相同的距离不再表示相同的差值。

三、方法二:数据提前进行对数转换

ggplot(Animals, aes(x = log10(body), y = log10(brain), label = rownames(Animals))) +

geom_text(size = 3)

四、其他对数,如以2或自然常数e的对数

方法:除了以10为底的对数,其他对数要完整定义。

library(scales)

# x使用自然对数标尺坐标轴,y使用以2为底的对数标尺坐标轴

animals_plot +

scale_x_continuous(

trans = log_trans(),

breaks = trans_breaks("log", function(x) exp(x)),

labels = trans_format("log", math_format(e^.x))

) +

scale_y_continuous(

trans = log2_trans(),

breaks = trans_breaks("log2", function(x) 2^x),

labels = trans_format("log2", math_format(2^.x))

)
温馨提示:答案为网友推荐,仅供参考
相似回答
大家正在搜