条形图不只显示一个x值的条形图

时间:2019-08-29 12:25:16

标签: r plotly

定义x轴的日期范围时,plotly条形图出现问题。

当存在一个或多个具有相同x值的数据点时,条形图不会显示在图中。如果至少有两个不同的x值,或者如果我不使用x轴范围,则这些条将如期显示。

下面是一个示例(我目前正在使用lubridate处理日期)。

library(lubridate)
library(plotly)

# Same x-value: bar does not show
plot_ly(x = c(ymd("2019-08-25"), ymd("2019-08-25")), y = c(1, 2), type = "bar") %>%
    layout(xaxis = list(range = ymd(c("2019-08-20", "2019-08-30"))))

# Different x-values: bars are shown
plot_ly(x = c(ymd("2019-08-25"), ymd("2019-08-26")), y = c(1, 2), type = "bar") %>%
    layout(xaxis = list(range = ymd(c("2019-08-20", "2019-08-30"))))

# No x-axis range defined, same x-values: the bar is shown
plot_ly(x = c(ymd("2019-08-25"), ymd("2019-08-25")), y = c(1, 2), type = "bar")

有解决方案吗?

编辑:为了进行比较,ggplot2没有相同的问题:

# ggplot works like expected
library(lubridate)
library(ggplot2)

ggplot(NULL, aes(x = ymd(c("2019-08-25", "2019-08-25")), y = c(1, 2))) +
    geom_col() +
    xlim(ymd(c("2019-08-20", "2019-08-30")))

1 个答案:

答案 0 :(得分:2)

您的代码实际上是在您的第一个版本中理解的,但是您需要设置条的宽度,以便最终显示它们。

我不确定单位是多少(可能是几毫秒?),因此您可能需要尝试使用它或进行研究以获取适合您实际情况的宽度。

class Question {
    constructor(question, ansA, ansB, ansC, ansD, answer) {
        this.question = question;
        this.ansA = ansA;
        this.ansB = ansB;
        this.ansC = ansC;
        this.ansD = ansD;
        this.answer = answer;
    };

    checkAns(ansSelected, answer) {
        if (ansSelected === answer) {
            console.log('Well Done')
        };
    };
};

//Questions
var questionOne = new Question('Where is Creete?',
                               'Barcalona', 'Greece', 'Dubi', 'Ireland', 'Greece');
var questionTwo = new Question('How many times have Liverppool won the Champions Legue?',
                               '1', '4', '6', '5', '6');
var questionThree = new Question('Where was the first Godfather in the mafia from?',
                                 'Milan', 'Gunoa', 'Rome', 'Napoli', 'Napoli');

//Index of the array with the questions array 
var i = 0;
const arrayQuestion = [questionOne, questionTwo, questionThree];


//Displaying the first index of the question array on load up
document.getElementById('question').innerHTML = arrayQuestion[i].question;
document.getElementById('rad1').innerHTML = arrayQuestion[i].ansA;
document.getElementById('rad2').innerHTML = arrayQuestion[i].ansB;
document.getElementById('labelRad3').innerHTML = arrayQuestion[i].ansC;
document.getElementById('rad4').innerHTML = arrayQuestion[i].ansD;

enter image description here