简体   繁体   English

我如何 plot R 条形图上的一条线

[英]how can i plot a line on bar chart in R

H <- c(1,2,4,1,0,0,3,1,3)
M <- c("one","two","three","four","five")
barplot(H,names.arg=M,xlab="number",ylab="random",col="blue",
    main="bar chart",border="blue")

I want to add line on the bar chart, i don't know how to do it我想在条形图上添加线条,我不知道怎么做

like the one in blue就像那个蓝色的

图片

Maybe you want this?也许你想要这个?

hist(H, breaks=-1:4, freq=FALSE, xaxt="n")
axis(side=1, at=seq(-0.5, 3.5), labels=M)
lines(density(H))

在此处输入图像描述

The graph in the question can be made with code following the lines of:问题中的图表可以使用以下行的代码制作:

1. Table the x vector. 1.x向量。

tbl <- table(H)
df1 <- as.data.frame(tbl)

2. With package ggplot2 , built-in ways of fitting a line can be used. 2.使用package ggplot2 ,可以使用内置的拟合线方式。

ggplot(df1, aes(as.integer(Var1), Freq)) +
  geom_bar(stat = "identity", fill = "red", alpha = 0.5) +
  geom_smooth(method = stats::loess, 
              formula = y ~ x, 
              color = "blue", fill = "blue",
              alpha = 0.5)

在此处输入图像描述

Test data creation code.测试数据创建代码。

set.seed(2020)
f <- function(x) sin(x)^2*exp(x)
p <- f(seq(0, 2.5, by = 0.05))
p <- p/sum(p)
H <- sample(51, size = 1e3, prob = p, replace = TRUE)

Edit编辑

Here is a new graph, with the new data posted in comment.这是一个新图表,新数据已在评论中发布。 The data is at the end of this answer.数据在这个答案的末尾。

library(ggplot2)
library(scales)

Mdate <- as.Date(paste0(M, "/2020"), format = "%d/%m/%Y")
df1 <- data.frame(H, M = Mdate)


ggplot(df1, aes(M, H)) +
  geom_bar(stat = "identity", fill = "red", alpha = 0.5) +
  geom_smooth(method = stats::loess, 
              formula = y ~ x, 
              color = "blue", fill = "blue", alpha = 0.25,
              level = 0.5, span = 0.1) +
  scale_x_date(labels = date_format("%d/%m"))

在此处输入图像描述

New data新数据

H <- c(1,2,4,1,0,0,3,1,3,3, 6,238,0,
       58,17,64,38,3,10,8, 10,11,13,
       7,25,11,12,13,28,44)  
M <- c("29/02","01/03","02/03","03/03",
       "04/03","05/03","06/03","07/03",
       "08/03", "09/03","10/03","11/03",
       "12/03","13/03","14/03","15/03",
       "16/03", "17/03","18/03","19/03",
       "20/03","21/03","22/03","23/03",
       "24/03", "25/03","26/03","27/03",
       "28/03","29/03")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM