说我有以下数据框:
line_df <- data.frame(x_ini = c(0.55,2.55,1.55,5.55,7.55),
x_end = c(1.45,3.45,2.45,6.45,8.45),
y = c(-0.5,-0.5,-1.5,-2.5,-2.5),
category = c("red","red","blue","green","green"))
我想为数据帧的每一行绘制一个水平段,其极限为(x_ini[i],y[i])
和(x_end[i],y[i])
,图例由line_df$category
给出。
我已经尝试过使用geom_segment
,segments
,abline
和lines
,但我无法通过相同的指令正确设置图例并绘制线段。我在用另一个数据帧的ggplot
完成绘制后得到了它(因此不在plot
指令之后),看来这也引起了我的问题。
关于如何执行此操作的任何建议?很高兴将数据帧修改为其他更合适的结构,但是我想避免为每个段重复调用同一条指令。
谢谢!
编辑
看起来像之前的代码
previous_df <- data.frame(letter=c("x","y","y","z","x","p"),number=c(9,3,2,1,5,7),labeldf=c(1,15,12,15,1,12))
ggplot(previous_df,aes(labeldf,number,fill=letter)) +
geom_bar(stat="identity",position='dodge')
因此,问题是我无法向其添加另一个ggplot
,如果直接添加geom_segment
(在Nova的答案中提到),则会出现有关fill
选项的错误。
我想如果您为“行”添加字段,您可以做到-这是您的意思吗?
line_df$row <- seq_len(nrow(line_df))
ggplot(line_df) +
geom_segment(aes(x = x_ini, xend = x_end, y = y, yend = y,
group = row, color = category), size = 2) +
scale_color_manual(values = c("lightblue", "seagreen", "firebrick"))
如果要从另一个数据框中添加数据,则可以这样操作:
ggplot(previous_df) +
geom_bar(aes(labeldf, number, fill=letter), stat="identity",position='dodge') +
geom_segment(data = line_df, aes(x = x_ini, xend = x_end, y = y, yend = y,
group = row, color = category), size = 2) +
scale_color_manual(values = c("lightblue", "seagreen", "firebrick"))