Search code examples
rplotly

My R code is not plotting the visual correctly


I am trying to recreate this in R visual in Power BI using columns and tables:

library(plotly)

dat <- data.frame(
    time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
    total_bill = c(14.89, 17.23)
)

p <- ggplot(data=dat, aes(x=time, y=total_bill)) +
    geom_bar(stat="identity")

p

Here is what I have come up with:

library(plotly)
   
p <- ggplot(dataset['Meal'],dataset['Number'], aes(x=time, y=total_bill)) +
    geom_bar(stat="identity")
p
 

But I am getting errors. This is what the table looks like:

Meal    Number
Dinner  14.89
Lunch   17.23

For those wondering where 'dataset' comes from. In Power BI, I selected the R visual and it creates a small R widget with a text box where I can enter the script. Then it allows me to drag and drop columns from tables which are already in the report. Here is an image:

enter image description here

Notice how the columns are automatically defined when I drag the columns in.

# The following code to create a dataframe and remove duplicated rows is always executed and acts as a preamble for your script: 

# dataset <- data.frame(Meal, Number)
# dataset <- unique(dataset)

# Paste or type your script code here:

Solution

  • I had to edit the x and y inputs in order to reproduce the example, but your issue seems to be a missing closing parenthesis on this line

    time = factor(x,
    

    This code gets me the result I think you're after

    x<-c("Dinner", "Lunch")
    y<-c(14.89,17.23)
    
    dat <- data.frame(
      time = factor(x),
                    total_bill = y
      )
      p <- ggplot(data=dat, aes(x=time, y=total_bill)) +
        geom_bar(stat="identity")
      p
    

    Update: Thanks for the additional info. I'm unfamiliar with Power BI, but it looks to me like the issue might be that the columns in 'dataset' might be unnamed (or at least it's unclear what the column names are). We can set the column names which should then allow us to plot as intended:

    colnames(dataset)<- c("time", "total_bill") 
    
     p <- ggplot(data=dataset, aes(x=time, y=total_bill)) +
        geom_bar(stat="identity")
      p