R极坐标方程玫瑰曲线图问题
我试图用R绘制R中的极坐标方程.但是,当我绘制玫瑰曲线时,我没有在图中得到正确数量的花瓣.
I am trying to graph polar equations in R using plotly. However, when I graph a rose curve, I'm not getting the right amount of petals in the graph.
我的代码...
library(plotly)
f <- function(){
output <- matrix(ncol=2, nrow = 361)
for (i in 0:360){
output[i,1] <- i
output[i,2] <- 3 * cos(2 * (i * pi/180))
}
return(output)
}
mf <- f()
df <- data.frame("theta" = mf[,1], "r"=mf[,2])
p <- plot_ly(
df,
type = 'scatterpolar',
mode = 'lines'
) %>%
add_trace(
r = ~r,
theta = ~theta,
name = 'Function',
line = list(
color = 'red'
)
) %>%
layout(
title = 'Polar Graph',
font = list(
family = 'Arial',
size = 12,
color = '#000'
),
showlegend = F
)
p
结果图...
图形应类似于...
有人可以告诉我我在做什么错吗,或者是否有更简单的方法可以在R中做到这一点?谢谢.
Can anyone tell me what I'm doing wrong or if there's an easier way to do this in R? Thanks.
对于常见的极坐标图,我习惯于半径为零的中心,但在您的情况下,图的中心的半径为-3.因此,使用plot_lt()时不会获得预期的结果. plot_lt()可能允许您在配置中进行更改,但我找不到它.
For common polar plot, I am used to the center having zero radius, but in your case the center of the plot has -3 as radius. Therefor you don’t get the expected result when using plot_lt(). it is possible that plot_lt() allow you to change this in the configuration, but I couldn’t find it.
可能的解决方案是移动角度和半径,以使半径始终大于零.这在下面的函数"shift_center_zero"中完成.对于每个负半径,乘以-1即可为正,对于这些行进行角度偏移,以使半径位于中心的另一侧.角度偏移是通过增加半个圆(180度)并采用完整圆的模量(360度)来限制角度,使其在单个圆内.
A possible solution is to shift the angels and radius such that the radius is always larger than zero. This is done in the function "shift_center_zero" below. For every negative radius, multiply by -1 to make positive, and for those rows make an angle shift such that the radius is on the other side of the center. The angle shift is done by adding half a round (180 degrees) and take modulus of a complete round (360 degrees) to restrict the angle such that it is within a single round.
shift_center_zero <- function(m){
m_negative <- m[,2]<0 # get negative rows
m[m_negative,1] <- (m[m_negative,1]+180)%%360 # angle shift
m[m_negative,2] <- -1*m[m_negative,2] # radius shift
return(m)
}
其余的代码几乎相同,使用nrow = 360插入361,以删除NA,并使用新的"shift_center_zero"功能.
The rest of your code is pretty much the same, with nrow = 360 insted of 361 to remove NA's and the use of the new "shift_center_zero" function.
library(plotly)
f <- function(){
output <- matrix(ncol=2, nrow = 360)
for (i in 0:360){
output[i,1] <- i
output[i,2] <- 3 * cos(2 * (i * pi/180))
}
return(output)
}
mf <- f()
# make the shift
mf<-shift_center_zero(mf)
df <- data.frame("theta" = mf[,1], "r"=mf[,2])
p <- plot_ly(
df,
type = 'scatterpolar',
mode = 'lines'
) %>%
add_trace(
r = ~r,
theta = ~theta,
name = 'Function',
line = list(
color = 'red'
)
) %>%
layout(
title = 'Polar Graph',
font = list(
family = 'Arial',
size = 12,
color = '#000'
),
showlegend = F
)
p