有关以下数据示例:
date a b
0 2010/3/31 12.2 71,168.00
1 2010/6/30 11.4 149,914.90
2 2010/9/30 10.9 231,281.60
3 2010/12/31 10.6 320,102.60
4 2011/3/31 10.2 98,902.80
5 2011/6/30 10.1 209,217.00
6 2011/9/30 9.9 324,440.50
7 2011/12/31 9.6 451,480.10
8 2012/3/31 8.1 106,938.50
9 2012/6/30 7.9 225,695.90
10 2012/9/30 7.8 349,612.90
11 2012/12/31 7.9 486,983.30
我已经使用下面的代码绘制了条形混合和y轴双线图:
df$date <- as.yearqtr(df$date, format = "%Y-%m-%d")
df_m <- melt(df, id.vars='date')
df_m_x <- df_m %>%
filter(variable %in% c("b"))
df_m_ratio_x <- df_m %>%
filter(variable %in% c("a")) %>%
coeff = 1/10000
ggplot() +
geom_bar(data = df_m_x, aes(x = date, y = value, fill = variable), alpha = 1.0, stat = 'identity') +
geom_line(data = df_m_ratio_x, aes(x = date, y = value, col = variable), size = 0.5) +
geom_point(data = df_m_ratio_x, aes(x = date, y = value, col = variable), size = 1) +
xlab('') +
scale_y_continuous(
name = "dollar",
sec.axis = sec_axis(~.*coeff, name = "%")) +
scale_color_manual(values = c("a" = "#00AFBB")) +
scale_x_yearqtr(limits = c(min(df$date), max(df$date)), format = "%YQ%q")
出局:
但是,我同时得到一个Removed 2 rows containing missing values (geom_bar)
,您可能会发现在图中,2010/3/31
和2012/12/31
的数据点丢失了。
有人可以帮助我弄清楚我在哪里做错了这个问题?非常感谢。
答案 0 :(得分:1)
感谢@teunbrand,添加scale_x_yearqtr(oob = scales::oob_keep, ...)
后,它可以正常工作。
ggplot() +
geom_bar(data = df_m_x, aes(x = date, y = value, fill = variable), alpha = 1.0, stat = 'identity') +
geom_line(data = df_m_ratio_x, aes(x = date, y = value, col = variable), size = 0.5) +
geom_point(data = df_m_ratio_x, aes(x = date, y = value, col = variable), size = 1) +
xlab('') +
scale_y_continuous(
name = "dollar",
sec.axis = sec_axis(~.*coeff, name = "%")) +
scale_color_manual(values = c("a" = "#00AFBB")) +
scale_x_yearqtr(oob = scales::oob_keep, limits = c(min(df$date), max(df$date)), format = "%YQ%q")