Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用y变量a factor向R中的绘图图表添加垂直线_R_Plotly - Fatal编程技术网

如何使用y变量a factor向R中的绘图图表添加垂直线

如何使用y变量a factor向R中的绘图图表添加垂直线,r,plotly,R,Plotly,我有一个data.frame,其中我在y轴上绘制了一个值id,与另一个值s排序的x轴上的值t相对 library(plotly) library(dplyr) # create data.frame df <- data.frame(id=c("a","b","c"),s=c(1,3,2),t=c(3,2,1)) # set order levels <- df %>% arrange(s) %>% .$id #[1] a c b # plot df %>

我有一个data.frame,其中我在y轴上绘制了一个值id,与另一个值s排序的x轴上的值t相对

library(plotly)
library(dplyr)

# create data.frame
df <- data.frame(id=c("a","b","c"),s=c(1,3,2),t=c(3,2,1))

# set order
levels <- df %>% 
arrange(s) %>% 
.$id #[1] a c b

# plot
df %>% 
mutate(id=factor(id, levels = levels)) %>%
plot_ly(x=~t,y=~id) %>% 
add_markers() 
library(plotly)
图书馆(dplyr)
#创建data.frame
df%
.$id#[1]a c b
#密谋
df%>%
突变(id=因子(id,级别=级别))%>%
绘图(x=~t,y=~id)%>%
添加_标记()
这个很好用

但是我想添加一条垂直线,表示t的平均值,用s加权

line <- weighted.mean(df$t,df$s)

line为了防止使用分类值对y轴进行绘图排序,可以绘制多条显示为一条的线

p <- add_lines(p, 
               x = rep(line, nrow(df)), 
               y = df$id)
p%
绘图(x=~t,y=~id)%>%
添加_标记()

直线我希望在加权平均点处有一条垂直线(因此在本例中为1.83),在我的图中从“a”一直延伸到“b”。x_值=weighted.mean(df$t,df$s)将行放置在正确的位置,但是类似于y_值=c(as.character(levels[1]),as.character(levels[length(levels)])的东西会根据需要将行放置在a和b之间,但会将y轴重新排序为字母顺序,这不是我所希望的want@pssguy:谢谢你的澄清!请参阅更新的答案。@Maximillian Peters非常感谢。在修正后的代码中,我认为我们现在可以不用x_值和y_值。更重要的是,我认为它应该是nrow(df)而不是length(df)。我认为后者仅在本例中有效,因为行数等于列数。如果你能确认我在这里是正确的,那么我将把这个勾选为answer@MP我也编辑了最终的解决方案。以供同行审查。我以前没有这样做过correctly@pssguy:lgtm:)
library(plotly)
library(dplyr)

# create data.frame
df <- data.frame(id=c("a","b","c"),s=c(1,3,2),t=c(3,2,1))

# set order
levels <- df %>% 
  arrange(s) %>% 
  .$id #[1] a c b

# plot
p <- df %>% 
  mutate(id=factor(id, levels = levels)) %>%
  plot_ly(x=~t,y=~id) %>% 
  add_markers()

line <- weighted.mean(df$t,df$s)


p <- add_lines(p, 
               x = rep(line, nrow(df)), 
               y = df$id)
p