R语言中具有2个y轴和相同x轴的条形图 [英] Bar Plot with 2 y axes and same x axis in R language

查看:158
本文介绍了R语言中具有2个y轴和相同x轴的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制具有两个不同 y 轴和相同 x 轴的条形图.

I am trying to plot a bar graph with two different y axes and same x axis.

出于某种原因,我无法在 R 中使用 barplot 进行绘图.我尝试使用 plot 函数进行相同的操作.但不能接近我想要的.

For some reason, I am not able to plot using barplot in R. I tried the same with plot function. But can not come close to what I wanted.

这是数据:

x,y1,y2
1,130,1525157
2,84,1070393
3,140,1263374
4,346,2620949
5,354,2939962
6,300,3303101
7,127,1647361
8,69,1168261
9,44,7447573
10,38,12804778
11,12,570379
12,22,3100184
13,7,236046
14,23,2322048

用于尝试的代码如下:

options(scipen=10000000)
bargraph_test <- read.csv(file="data_test.csv",head=TRUE,sep=",")
attach(bargraph_test)
plot(x = x, y = y1, col = "blue", type = "h", xlab = "x", ylab = "y1", main = "")
par(new = T)
plot(x = x, y = y1, col = "green", type = "h", xaxt = "n", yaxt = "n", xlab = "", ylab = "")
axis(4)
mtext("y2", side = 4, line = 3)

我在此处附上了我得到的输出的屏幕截图.

I am attaching the screenshot here of the output I get.

我需要将这些线条显示为条形图案.

I need to display these lines as bar patterns.

有人能帮我解决这种情况吗.

Can someone help me with this situation.

感谢大家的帮助.

推荐答案

使用 highcharter 您可以添加任意数量的 Y 轴.只需在 hc_yAxis_multiples 中添加另一个条目 &hc_add_series.

Using highcharter you can add as many Y-axis you want. Simply add another entry in hc_yAxis_multiples & hc_add_series.

library(highcharter)

highchart() %>% 
  hc_yAxis_multiples(
    list(lineWidth = 3, lineColor='blue', title=list(text="y1")),
    list(lineWidth = 3, lineColor="green", title=list(text="y2"))
  ) %>% 
  hc_add_series(data = df$y1, color='blue', type = "column") %>% 
  hc_add_series(data = df$y2, color='green', type = "column", yAxis = 1) %>%
  hc_xAxis(categories = df$x, title = list(text = "x"))

输出图:

#sample data
> dput(df)
structure(list(x = 1:14, y1 = c(130L, 84L, 140L, 346L, 354L, 
300L, 127L, 69L, 44L, 38L, 12L, 22L, 7L, 23L), y2 = c(1525157L, 
1070393L, 1263374L, 2620949L, 2939962L, 3303101L, 1647361L, 1168261L, 
7447573L, 12804778L, 570379L, 3100184L, 236046L, 2322048L)), .Names = c("x", 
"y1", "y2"), class = "data.frame", row.names = c(NA, -14L))

这篇关于R语言中具有2个y轴和相同x轴的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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