如何在R中固定ggplot双y轴 [英] How to fix ggplot double y axis in r

查看:49
本文介绍了如何在R中固定ggplot双y轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制带有两个y轴的图形.我知道还有很多与此类似的问题,但我似乎无法根据其他帖子来弄清楚

I am trying to make a graph with two y axis. I know there are a lot of other questions out there similar to this but I just cant seem to figure it out based on other posts

所以我遇到的问题是y轴刻度.这是我在做什么

So the issue I am having is the y axis scale. Here is what I am doing

Time <- c("June-2018-30", "July-2018-31", "August-2018-31", "September-2018-30",
            "October-2018-31", "November-2018-30", "December-2018-31", "January-2019-31", 
            "February-2019-28", "March-2019-31", "April-2019-30", "May-2019-31")

Bitcoin <- c(3.469861e-17, 3.188903e-17, 2.685114e-17, 2.42335e-17, 2.322641e-17, 
              2.447058e-17, 3.18029e-17, 2.944836e-17, 2.839419e-17, 2.76008e-17, 
              2.661607e-17, 2.536966e-17)

`USD Return` <- c(2.35e-13, 2.27e-13, 1.80e-13, 1.60e-13, 1.51e-13, 1.33e-13, 1.18e-13, 
                  1.08e-13, 1.047e-13, 1.09e-13, 1.37e-13, 1.83e-13)

total.values3 <- data.frame(Time, Bitcoin,`USD Return`, stringsAsFactors = F)

library(ggplot2)

ggplot(data=total.values3, aes(x=Time, y=`USD Return`, group=1)) +
  geom_line(aes(y = `USD Return`), color = "blue") +
  geom_line(aes(y = Bitcoin), color = "red") + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
  scale_y_continuous("USD Return", 
                      sec.axis = sec_axis(~./10000, name = "Bitcoin Return")) + 
  scale_x_date(labels=date_format("%B-%Y-%d"), 
               date_labels = "%B-%Y", breaks = total.values3$Time)

这是输出内容的图片

我不确定出了什么问题.我可以看到比例尺是错误的.我不明白为什么比特币线只是一条直线.我也不知道为什么右边的y轴变成负数

I am not sure what is going wrong. I can see that the scale is wrong. I can't figure out why the bitcoin line is just a straight line. I also don't know why the y axis on the right side goes into the negative

推荐答案

total.values3$Time <- as.Date(total.values3$Time, format = "%B-%Y-%d")

ggplot(data=total.values3, aes(x=Time, group=1)) +
  geom_line(aes(y = `USD Return`), color = "blue") +
  geom_line(aes(y = Bitcoin*10000), color = "red") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_y_continuous("USD Return", 
                     sec.axis = sec_axis(~./10000, name = "Bitcoin Return")) + 
  scale_x_date(labels=date_format("%B-%Y-%d"), 
                      date_labels = "%B-%Y", breaks = total.values3$Time)

这应该可以解决问题.

这篇关于如何在R中固定ggplot双y轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆