AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 76930801
Accepted
Victor Nielsen
Victor Nielsen
Asked: 2023-08-18 23:42:09 +0800 CST2023-08-18 23:42:09 +0800 CST 2023-08-18 23:42:09 +0800 CST

Plotly começa na etapa errada do controle deslizante, mesmo depois de especificar

  • 772

Eu tenho o código abaixo, e o problema é que o controle deslizante não começa na posição do meio - ele começa na posição 4/5 em vez de t=650600. O gráfico mostrado na imagem é corretamente o da posição do meio ( t=600). Enquanto isso, o título aparece em t=700, mas vamos ignorá-lo por enquanto, a menos que você saiba por quê.

library(plotly)

x <- seq(0, 50, by = 0.1)
t_values <- seq(500, 700, by = 50)  # Adjusted t values

# Fixed y-axis range
y_range <- c(0, get_density(0, inc, 700, get_u(inc, 700, target_population)))  # Adjust this to your desired y-axis range

# create steps and plot all traces
steps <- list()
fig <- plot_ly()

aval <- list()
slider_steps <- list()

initial_slider_value <- 600  # Initial slider value

for (i in 1:length(t_values)) {
  t_value <- t_values[i]
  # Update u value based on the current t value
  u <- get_u(inc, t_value, target_population)

  # Update the border and population based on the new u value
  border_value <- get_border(target_border, inc, t_value, u)
  population_value <- get_population(inc, t_value, u)

  # Update the title to include the current t_value
  title_text <- paste("Transport cost:", t_value)

  aval[[i]] <- list(visible = t_value == initial_slider_value,  # Show line for the initial slider value
                    name = paste0('v = ', t_value),
                    x = x,
                    y = get_density(x, inc, t_value, u))

  fig <- add_lines(fig, x = aval[i][[1]]$x, y = aval[i][[1]]$y, visible = aval[i][[1]]$visible,
                   name = aval[i][[1]]$name, type = 'scatter', mode = 'lines', hoverinfo = 'name',
                   line = list(color = '00CED1'), showlegend = FALSE)

  step <- list(args = list('visible', rep(FALSE, length(aval))),
               method = 'restyle')
  step$args[[2]][i] = TRUE
  steps[[i]] = step

  # Define the slider step
  slider_steps[[i]] <- list(
    label = t_value,
    method = 'restyle',
    args = list('visible', rep(FALSE, length(t_values)))
  )
  slider_steps[[i]]$args[[2]][i] = TRUE
}

# Find the index of the initial slider value
initial_slider_index <- which(t_values == initial_slider_value)

# add slider control to plot
fig <- fig %>%
  layout(sliders = list(
    list(currentvalue = list(prefix = "Transport cost: "),
         steps = slider_steps,
         active = initial_slider_index  # Set the initial active slider
    )
  ),
  title = title_text,  # Set the initial title
  yaxis = list(range = y_range),  # Set fixed y-axis range
  xaxis = list(range = c(0, 50))  # Set the desired x-axis range
  )

fig

Por isso, especifiquei especificamente que quero que comece na marca 600 (no meio).

Imagem

Se você quiser testar o código, adicione isto acima:

alpha = 0.86 # Expenditure share on all other goods
beta = 0.6 # Cost share of housing capital in housing production function
g = 0.0005 # Scaling on housing production function
theta = 3 # Radians available for construction (benchmark is 3)
target_population <- 2000000
target_border <- 40
inc <- 70000
t <- 600
ra <- 45000
u <- 5353.65
x <- 0

get_price <- function(x,inc,t,u) {
  (((alpha^alpha) * ((1 - alpha)^(1 - alpha)) * (inc - t * x)) / u)^(1 / (1 - alpha))
}

get_quantity <- function(x,inc,t,u) {
  (((1 - alpha) * (inc - t * x)) / (((alpha^alpha) * ((1 - alpha)^(1 - alpha)) * (inc - t * x)) / u)^(1 / (1 - alpha)))
}

get_capital_intensitinc <- function(x,inc,t,u) {
  (1 / (get_price(x,inc,t,u) * (beta) * (g)))^(1 / (beta - 1))
}

get_rent <- function(x,inc,t,u) {
  (get_price(x,inc,t,u) * (g)) * ((1/(get_price(x,inc,t,u) * (beta) * (g)))^(beta / (beta - 1))) - 1 * ((1 / (get_price(x,inc,t,u) * (beta) * (g)))^(1 / (beta - 1)))
}

get_far <- function(x,inc,t,u) {
  (g) * get_capital_intensitinc(x,inc,t,u)^(beta)
}

get_density <- function(x,inc,t,u) {
  get_far(x,inc,t,u) / get_quantity(x,inc,t,u)
}

get_border <- function(target_border,inc,t,u) {
  uniroot(\(x) get_rent(x,inc,t,u) - ra, lower = 0, upper = 100)$root
}

get_population <- function(inc,t,u) {
  theta * integrate(\(x) {x * get_density(x,inc,t,u)},lower = 0, upper = get_border(target_border,inc,t,u))$value
}

get_u <- function(inc,t,target_population) {
  uniroot(\(u) get_population(inc,t,u) - target_population, c(4500, 6500))$root
}

u <- get_u(inc,t,target_population)
  • 1 1 respostas
  • 14 Views

1 respostas

  • Voted
  1. Best Answer
    Skenvy
    2023-08-19T00:04:11+08:002023-08-19T00:04:11+08:00

    As listas R são indexadas a partir de 1 . O controle deslizante do Plotly é indexado a partir de 0 . Apenas subtraia 1 de tudo o que você obtiver da which(...)lista antes de entregá-la active.

    • 1

relate perguntas

  • Adicionar número de série para atividade de cópia ao blob

  • A fonte dinâmica do empacotador duplica artefatos

  • Selecione linhas por grupo com 1s consecutivos

  • Lista de chamada de API de gráfico subscritoSkus estados Privilégios insuficientes enquanto os privilégios são concedidos

  • Função para criar DFs separados com base no valor da coluna

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve