问题描述
我正在尝试重新创建图,并且在那里有几行,这些行在图例中,但在此旁边,图也有一些要点。我怎么能在这些点上放置标签。请注意,这些点不在数据框中。我的代码现在看起来像这样:
ggplot(df,aes(x=tau_3)) +
geom_line(aes(y= a1,color = "blue")) +
geom_line(aes(y= a2,color = "green"))+
xlim(0,0.6) +
ylim(0,0.4) +
geom_point(aes(0,0),size =5,shape = "square") +
geom_point(aes(0,1/6),shape = "circle") +
geom_point(aes(0,0.1226),shape = "triangle") +
scale_color_discrete(name = "Legend",labels = c("GLO","GEV"))
解决方法
要标记点,您可以添加fname=input('Enter the file name: ')
fhand = open(fname)
biglist=[]
counts=dict()
count=0
secondlist=[]
for line in fhand:
line=line.strip()
word=line.split()
if len(word)<1:
continue
if word[0]!='From':
continue
words=word[5]
words=words.split(':')
num=words[0]
**counts[num]=counts.get(num,0)+1**
counts=counts.items()
counts_sorted=sorted(counts)
for k,v in counts_sorted:
print(k,v)
层以及点坐标和标签。
使用geom_text
作为示例数据集,请尝试以下操作:
mtcars
解决问题的一种方法是将点的坐标和形状放在辅助数据框df_points
中,并在geom_point
和geom_text
中使用它们。
对于行,调整数据https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html的形状,一次调用geom_line
就足够了。设置参数inherit.aes = FALSE
,对于geom_point
,还要设置show.legend = FALSE
。
library(ggplot2)
library(dplyr)
library(tidyr)
df_points <- data.frame(x = rep(0,3),y = c(0,1/6,0.126),shape = factor(c("square","circle","triangle"),levels = c("square","triangle")))
df %>%
pivot_longer(
cols = starts_with('a'),names_to = 'y',values_to = 'a'
) %>%
ggplot(aes(tau_3,a,color = y)) +
geom_line() +
geom_point(data = df_points,mapping = aes(x,y,shape = shape),size = 5,show.legend = FALSE,inherit.aes = FALSE) +
geom_text(data = df_points,label = shape),vjust = -1.5,hjust = 0,inherit.aes = FALSE) +
xlim(0,0.6) +
ylim(0,0.4) +
scale_color_manual(name = "Legend",values = c("blue","green"),labels = c("GLO","GEV")) +
scale_shape_manual(values = c("square","triangle"))
测试数据
set.seed(2020)
n <- 20
tau_3 <- runif(n,0.6)
a1 <- runif(n,0.4)
a2 <- runif(n,0.4)
df <- data.frame(tau_3,a1,a2)