简体   繁体   English

r 中的 xy 散点图,点上有标签

[英]x-y scatter-plot in r with labels on points

I am trying to make an xy scatter-plot.我正在尝试制作 xy 散点图。 I don't mind if it's in plot or ggplot2.我不介意它是在 plot 还是 ggplot2 中。 I don't know much about each, but I would like an example in both if you don't mind.我对每一个都不太了解,但如果你不介意的话,我想在这两个方面举个例子。 I would like a label on the points.我想要一个 label 就点。

Below is code and dput:以下是代码和输入:

tickers <- rownames(x2)

library(zoo)
plot(x2, 
     main= "Vol vs Div",
     xlab= "Vol (in %)",
     ylab= "Div",
     col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)

text(x=x2$Volatility101,y=x2$`12m yield`, labels=tickers,cex= 0.7, pos= 3)


x2: x2:

structure(list(Volatility101 = c(25.25353177644, 42.1628734949414, 
28.527736824123), `12m yield` = c("3.08", "7.07", "4.72")), class = "data.frame", row.names = c("EUN", 
"HRUB", "HUKX"))

Here is a tidyverse solution.这是一个tidyverse的解决方案。

library(ggplot2)
library(tidyr)
library(dplyr)
library(ggrepel)

x2 %>%
  rownames_to_column(var = "tickers") %>%
  ggplot(aes(x = Volatility101, y = `12m yield`)) +
  geom_point(color = "blue") +
  geom_text_repel(aes(label = tickers)) +
  ggtitle("Vol vs Div") +
  xlab("Vol (in %)") +
  ylab("Div") +
  theme_classic() 

在此处输入图像描述

I was surprised that the plot function worked at all.我很惊讶plot function 完全有效。 The Y-values are character values. Y 值是字符值。 Fixing that in the text call results in text being placed in the expected locations在文本调用中修复该问题会导致文本被放置在预期的位置

text(x=x2$Volatility101,y=as.numeric(x2$`12m yield`)+.1, labels=tickers,
            cex= 0.7, col='black')

A couple of notes about the question presentation: It's unclear (and misleading) why ggplot2 is a tag.关于问题介绍的几点说明:尚不清楚(且具有误导性)为什么 ggplot2 是一个标签。 The plot function is generic and in this case it uses base-graphics rather than either ggplot2 specifically or grid graphics more generally. plot function 是通用的,在这种情况下,它使用基本图形而不是ggplot2或更普遍的grid图形。 I also think that the library(zoo) call is probably unnecessary.我也认为library(zoo)调用可能是不必要的。 There is a plot.zoo function, but it would not be called in this case.有一个plot.zoo function,但在这种情况下不会被调用。

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

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