ggplot2 with dual axis

空扰寡人 提交于 2019-12-11 04:26:06

问题


This is an extension of this question. I am currently using the most recent version of ggplot2 (v2.2.0) from CRAN to create plots within R.

I am making use of the solution provided by @Axeman here.

The trouble I have is that when I use facets sometimes one of the y-axes shows very small values. I am wondering if someone has a clean solutions so that both y-axes can be scaled appropriately.

Reproducible example:

library(data.table)
library(ggplot2)
library(scales)

dt1 <- data.table(diamonds)
dt1 <- dt1[, .(averageprice = mean(price), numstones  =.N, Group = "Trend"), 
           by = color]

dt2 <- data.table(diamonds)
dt2 <- dt2[cut == "Premium", .(averageprice = mean(price), numstones = .N, Group = "Premium"), 
           by = color]

dt1 <- rbindlist(list(dt1, dt2))
setkey(dt1, color)

# rescale axes for plotting
max_left <- max(dt1[, sum(averageprice), by = .(Group, color)]$V1)
max_right <- max(dt1[, sum(numstones), by = .(Group, color)]$V1)
dt1$right <- dt1$numstones / (max_right / max_left)

dt1
# color averageprice numstones   Group     right
#     D     3169.954      6775   Trend 3776.6435
#     D     3631.293      1603 Premium  893.5734
#     E     3076.752      9797   Trend 5461.2216
#     E     3538.914      2337 Premium 1302.7330
#     F     3724.886      9542   Trend 5319.0748
#     F     4324.890      2331 Premium 1299.3883
#     G     3999.136     11292   Trend 6294.5916
#     G     4500.742      2924 Premium 1629.9491
#     H     4486.669      8304   Trend 4628.9664
#     H     5216.707      2360 Premium 1315.5540
#     I     5091.875      5422   Trend 3022.4296
#     I     5946.181      1428 Premium  796.0217
#     J     5323.818      2808   Trend 1565.2863
#     J     6294.592       808 Premium  450.4100

p <- ggplot()
p <- p + geom_col(data = dt1, aes(color, averageprice, fill = "myfill"))
p <- p + geom_point(data = dt1, aes(color, right, colour = "mycolour"))
p <- p + scale_y_continuous(sec.axis = sec_axis(trans = ~ . * (max_right / max_left),
                                                name = 'number of stones'))
p <- p + scale_fill_manual(name = "", labels = "Average Price", values = "#00AEFF")
p <- p + scale_colour_manual(name = "", labels = "Number of Stones", values = "#3c3c3c")
p <- p + guides(fill = guide_legend(order = 1))
p <- p + facet_wrap(~ Group, scales = "free_y")
p <- p + theme(legend.position = "bottom")
p

What I am hoping to be able to do is to have it so the right hand axis of the Premium facet has a maximum value that is more in line with the data (approx 4000). Obviously not wanting to hardcode things though.

Any guidance would be greatly appreciated.

来源:https://stackoverflow.com/questions/40837588/ggplot2-with-dual-axis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!