Our youtube channel

Our youtube channel has lots of videos on data visualisation in r.

Visit our youtube channel https://www.youtube.com/c/TechAnswers88

Video link https://youtu.be/OlIzlosMN3o

Barcharts in R using plotly

Data for charts


# Note that you do not need ggplot2 library for creating the plotly charts.
#We wanted to use the mpg built in dataset which comes with ggplot2. Hence we loaded the ggplot2 library as well.

library(ggplot2)
library(plotly)


data <- ggplot2::mpg

#Let us start by plotting a chart in ggplot
pl <- ggplot(data = data, aes(x = manufacturer))
pl <- pl + geom_bar(stat = "count")
pl



pl2 <- plotly::ggplotly(pl)
pl2

Using the count based on the x axis values

In this case we have 37 rows in our data where the manufacturer is ‘dodge’. Plotly automatically counts the frequency and uses it as y values. Notice that we are only supply the x axis value in the code below.

library(plotly)


pl <- plot_ly(data =mpg, x = ~ manufacturer )
pl

Data labels and their placement

library(dplyr)

data  <- mpg%>%group_by(manufacturer)%>%tally()
data

# Placing it outside the bars
pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "outside")%>%
      add_bars()
pl
# place it inside the bars pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside")%>% add_bars() pl

Width of bars

library(dplyr)


# width = 0.9
pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside")%>%
      add_bars(width = 0.9)
pl
# width = 0.2 pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside")%>% add_bars(width = 0.3) pl

Order the bars

library(dplyr)

pl <- plot_ly(data =data, x = ~ reorder(manufacturer, n) , y = ~ n, text= ~n , textposition = "inside")%>%
      add_bars(width = 0.9)
pl
pl <- plot_ly(data =data, x = ~ reorder(manufacturer, -n) , y = ~ n, text= ~n , textposition = "inside")%>% add_bars(width = 0.9) pl

Colour the bars

Each bar with same colour

library(dplyr)


pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside", color = I("black"))%>%
      add_bars(width = 0.9)
pl

Each bar with different colour based on a variable

library(dplyr)


pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside", color = ~ manufacturer)%>%
      add_bars(width = 0.9)
pl

Selectively colour a bar

library(dplyr)



pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside", 
              color =  ifelse(data$n == data$n[which.max(data$n)], "Max","Not max" ),
              colors = c('red', 'green'))  %>%
      add_bars(width = 0.9 )
  
pl

Using your own colour pallette

You can list your colours in the colors option. We have 15 manufacturers in our chart so we have to give 15 different colours inside the colours() option as shown below.

library(dplyr)


# different colour for each manufacturer
pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n 
              , textposition = "inside"
              , color = ~ manufacturer , colors = c('magenta1','maroon','mediumorchid2','mediumpurple4','mediumseagreen'
                  , 'mediumslateblue','mediumspringgreen','mediumturquoise','mediumvioletred','midnightblue','mintcream'
                  ,'mistyrose', 'red' ,'rosybrown' ,'royalblue'))%>%
      add_bars(width = 0.9)
pl

Control the tick angle

library(dplyr)


# different colour for each manufacturer
pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n 
              , textposition = "inside"
              , color = ~ manufacturer , colors = c('magenta1','maroon','mediumorchid2','mediumpurple4','mediumseagreen'
                  , 'mediumslateblue','mediumspringgreen','mediumturquoise','mediumvioletred','midnightblue','mintcream'
                  ,'mistyrose', 'red' ,'rosybrown' ,'royalblue'))%>%
      add_bars(width = 0.9)%>%
      layout(xaxis = list(title = "", tickangle = -45))
pl

Hide the legend

hide_legend = FALSE command will hide the legend. Notice the placement of the command for the showlegend = FALSE. It has been put under the layout command.

library(dplyr)


# different colour for each manufacturer
pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n 
              , textposition = "inside" 
              , color = ~ manufacturer , colors = c('magenta1','maroon','mediumorchid2','mediumpurple4','mediumseagreen'
                  , 'mediumslateblue','mediumspringgreen','mediumturquoise','mediumvioletred','midnightblue','mintcream'
                  ,'mistyrose', 'red' ,'rosybrown' ,'royalblue'))%>%
      add_bars(width = 0.9)%>%
     layout(showlegend = FALSE)
pl

Hovertext

When you are using your charts interactively in a browser eg, when you are using a shiny or flexdashboard, this feature is useful. If you are producing charts which are going to be used in a word, pdf, powerpoint etc then this feature is not of use to you.

library(dplyr)

# hoverinfo = "text" tells your chart that you only want to display the hovertext which you have specified.Otherwise it will show the default hover information as well as the hovertext which you defined..


# different colour for each manufacturer
pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside"
              , color = ~ manufacturer
              , hovertext = ~paste(manufacturer ,"\n", "Count=", n), hoverinfo = "text"
              
              )%>%
      add_bars(width = 0.9)
pl

Customise the headings using the layout

library(dplyr)

# different colour for each manufacturer
pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside"
              , color = ~ manufacturer
            , hovertext = ~paste(manufacturer ,"\n", "Count=", n), hoverinfo = "text"
              )%>%
      add_bars(width = 0.9)%>%
   layout(title ="Car Manufacturers data"
          , xaxis = list(title ="Manufacturers")
          , yaxis = list(title ="Count"))
pl

Selective annotations

library(dplyr)

# different colour for each manufacturer
pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside"
              , color = ~ manufacturer
            , hovertext = ~paste(manufacturer ,"\n", "Count=", n), hoverinfo = "text"
              )%>%
      add_bars(width = 0.9)%>%
   layout(title ="Car Manufacturers data"
          , xaxis = list(title ="Manufacturers")
          , yaxis = list(title ="Count"))%>%
  
    add_annotations(x = data$manufacturer[which.max(data$n)], y = data$n[which.max(data$n)],text  = "Highest")
pl

Horizontal legend orientation

Notice the placement of the command for the showlegend = FALSE. It has been put under the layout command.

library(dplyr)

# different colour for each manufacturer
pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside"
              , color = ~ manufacturer
            , hovertext = ~paste(manufacturer ,"\n", "Count=", n), hoverinfo = "text"
              )%>%
      add_bars(width = 0.9)%>%
   layout(title ="Car Manufacturers data"
          , xaxis = list(title ="Manufacturers")
          , yaxis = list(title ="Count")
          , showlegend = TRUE
          , legend = list(orientation = 'h') )%>%
  
    add_annotations(x = data$manufacturer[which.max(data$n)], y = data$n[which.max(data$n)],text  = "Highest")
pl

Vertical legend orientation

library(dplyr)

# different colour for each manufacturer
pl <- plot_ly(data =data, x = ~ manufacturer , y = ~ n, text= ~n , textposition = "inside"
              , color = ~ manufacturer
            , hovertext = ~paste(manufacturer ,"\n", "Count=", n), hoverinfo = "text"
              )%>%
      add_bars(width = 0.9)%>%
   layout(title ="Car Manufacturers data"
          , xaxis = list(title ="Manufacturers")
          , yaxis = list(title ="Count")
          , legend = list(orientation = 'v', title = 'Cars') )%>%
  
    add_annotations(x = data$manufacturer[which.max(data$n)], y = data$n[which.max(data$n)],text  = "Highest")
pl

Save chart as a static image for use in Word or Powerpoint.

library(htmlwidgets)
library(webshot)
htmlwidgets::saveWidget(widget = pl, file = "D:\\tmp\\myChart.html")
webshot::webshot(url = "D:\\tmp\\myChart.html" , file ="D:\\tmp\\myChart.png", delay = 4 )