In the Cartesian plane for X and Y coordinates, colors can be used to represent data on the graph to make it more understandable. This color label can be used to display continuous or discrete data both. Python Plotly can be used to display both the color representation i.e. continuous(moments in time) and discrete(categorical). In this article, we will display both color representations for discrete and continuous(color scale) using Python. Here firstly we will see the continuous color representation then on the same dataset, we will see discrete color representation.
Required Module:
The plotly.express module can create the entire Figure at once. It uses the graph_objects internally and returns the graph_objects.Figure instance.
pip install plotly-express
Continuous/Color-scale representation
Here we will first import the Plotly python library. As we are going see that in a certain restaurant on which day how much total bill is issued to the customers and how much total tips are given by the customers to the waiters. So ‘day’ is plotted to Y-axis and ‘total_bill’ is plotted to X-axis. The dataset is in-build with Plotly. No other dataset is need to be downloaded or put in input.
Python3
import plotly.express as pltx dataFrame = pltx.data.tips() figure = pltx.scatter(dataFrame, x = "total_bill" , y = "day" ,color = "tip" , title = "String 'tip' values\ (Total Bill vs Day) in mean continuous \ colors representation") figure.show() |
Output:
Discrete Color representation
Now we will plot the same graph with the discrete color technique. For discrete colors, we need to calculate the exact values of the ‘tip’ instead of the value range. For doing this simply we will convert the value range of ‘tip’ to the string and then we will plot it.
From the output, we can see that instead of a color scale that shows up the value range, discrete color representation is showing results with exact values. So, only with a single line of code, we can easily convert the representation from color-scale to discrete representation.
Python3
import plotly.express as pltx dataFrame = pltx.data.tips() # converting the values to string dataFrame[ "tip" ] = dataFrame[ "tip" ].astype( str ) figure = pltx.scatter(dataFrame, x = "total_bill" , y = "day" ,color = "tip" , title = "String 'tip' values(Total \ Bill vs Day) in mean discrete colors \ representation") figure.show() |
Output: