[英]R: Label X-axis on line chart with ggplot2
I have this data frame to construct some lines chart using ggplot2
.我有这个数据框来使用
ggplot2
构建一些折线图。 lb
is what I want my label to be on x-axis
while each other variables (x0.6, x0.8, x0.9, x0.95, x0.99, and x0.999) will be against lb
on the y-axis
. lb
是我希望我的标签位于x-axis
而其他变量(x0.6、x0.8、x0.9、x0.95、x0.99 和 x0.999)将在y-axis
上与lb
相对y-axis
。
# my data
lb <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
x0.6 <- c(0.9200795, 0.9315084, 0.9099002, 0.9160192, 0.9121120, 0.9134098, 0.9130619, 0.9128494, 0.9144164)
x0.8 <- c(0.9804872, 1.0144678, 0.9856382, 0.9730490, 1.0032707, 1.0036311, 0.9726198, 0.9986403, 1.0022643)
x0.9 <- c(1.055256, 1.016159, 1.067242, 1.089894, 1.043502, 1.041497, 1.037738, 1.023274, 1.040536)
x0.95 <- c(1.058024, 1.105353, 1.069076, 1.061077, 1.095764, 1.096789, 1.096670, 1.121497, 1.109918)
x0.99 <- c(1.107258, 1.098061, 1.118248, 1.101253, 1.083208, 1.109715, 1.083704, 1.083704, 1.118057)
x0.999 <- c(1.110732, 1.119625, 1.121221, 1.087423, 1.093228, 1.094003, 1.108910, 1.112413, 1.096734)
#my datafram
pos11 <- data.frame(lb, x0.6, x0.8, x0.9, x0.95, x0.99, x0.999)
#load packages
library("reshape2")
library("ggplot2")
# this `R` CODE reshapes the data
long_pos11 <- melt(pos11, id="lb")
# Here is the `R` code that produces the `line-chart`
pos_line <- ggplot(data = long_pos11,
aes(x=AR, y=value, colour=variable)) +
geom_line() geom_line()
I want the line-chart
to show elements of the vector lb
(1, 2, 3, 4, 5, 6, 7, 8, 9) on x-axis
as its label just like date
is 0n Plotting two variables as lines using ggplot2 on the same graph我希望
line-chart
在x-axis
显示向量lb
(1, 2, 3, 4, 5, 6, 7, 8, 9) 的元素作为它的标签,就像date
是 0n 使用绘制两个变量作为线ggplot2 在同一张图上
Try this.尝试这个。 As your variable is of numeric type you would need to set it as factor and then also add
group
to your aes()
statement.由于您的变量是数字类型,因此您需要将其设置为因子,然后还将
group
添加到您的aes()
语句中。 Here the code:这里的代码:
library("reshape2")
library("ggplot2")
# this `R` CODE reshapes the data
long_pos11 <- melt(pos11, id="lb")
# Here is the `R` code that produces the `line-chart`
pos_line <- ggplot(data = long_pos11,
aes(x=factor(lb), y=value, colour=variable,group=variable)) +
geom_line()+xlab('lb')
Output:输出:
We can also use pivot_longer
我们也可以使用
pivot_longer
library(ggplot2)
library(tidyr)
library(dplyr)
pos11 %>%
pivot_longer(cols = -lb) %>%
mutate(lb = factor(lb)) %>%
ggplot(aes(x = lb, y = value, color = name, group = name)) +
geom_line() +
xlab('lb')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.