Open In App

How to make histogram bars to have different colors in Plotly in R?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to discuss making histogram bars to have different colors in Plotly in R Language. The Histogram is defined as the bar graph representation of data along the x-axis. The plotly package contains plot_ly() function which is used to visualize different plots in R like scatter plots, histogram,pie chart etc,.

Syntax: plot_ly(df,type,marker,layout)

Where,

  • df -dataframe
  • type – used to specify the type of plot we want to visualize
  • marker – used to mark the plot with different colors using color attribute
  • layout – Contain attributes that are used to modify the properties of layout like Title etc,.

Create a histogram with different colors

First, we need to install and load the required package and then create the sample data frame which contains a vector of numbers. Using plot_ly() function we are going to plot the histogram and using marker attribute and we can specify list of colors we want to plot to different bars.

R




# install required packages
install.packages("plotly")
 
# Load the installed package
library(plotly)
 
# creation of sample dataframe (vector of numeric values)
df <- c(1,2,3,4,5,6,7,8)
 
# Plotting the scatter plot using plot_ly() function
plot_ly(x=df, type="histogram",
        marker=list(color=c('green','red',
                            'blue','yellow'))) %>%
  layout(title="Histogram using Plotly")


Output:

 


Last Updated : 24 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads