Going over the documentation https://plotly.com/python/table/ I wanted to plot a data frame as a table
The documentation suggested the following
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv')
fig = go.Figure(data=[go.Table(
header=dict(values=list(df.columns),
fill_color='paleturquoise',
align='left'),
cells=dict(values=[df.Rank, df.State, df.Postal, df.Population],
fill_color='lavender',
align='left'))
])
fig.show()
However, my dataframe is kind big and I wanted a better way to input the values of the columns. Something that would be better than
....values=[df.Rank, df.State, df.Postal, df.Population]....
You can plot data directly from your DataFrame using the plot () method: Scatter plot of two columns import matplotlib.pyplot as plt import pandas as pd # a scatter plot comparing num_children and num_pets df.plot(kind='scatter',x='num_children',y='num_pets',color='red') plt.show()
This is how the DataFrame would look like: Finally, plot the DataFrame by adding the following syntax: You’ll notice that the kind is now set to ‘line’ in order to plot the line chart. Here is the complete Python code: And once you run the code, you’ll get this line chart: Bar charts are used to display categorical data.
Knowing how to plot a Dataframe will help you perform better data analysis in just a few lines of code. Visualizing a Dataframe is one of the first activities carried out by Data scientists to understand the data better.
Types of Plotly data visualizations we can create on a dataframe. Plotly has several different chart types. A few of them are available through cufflinks which we can directly call from a dataframe. This is How I Create Dazzling Dashboards Purely in Python.
After a bit of search I found an easy replacement. Pandas allows converting a whole dataframe into a list of lists.
Simply replace the line with
df.transpose().values.tolist()
So the final code looks like this
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv')
fig = go.Figure(data=[go.Table(
header=dict(values=list(df.columns),
fill_color='paleturquoise',
align='left'),
cells=dict(values=df.transpose().values.tolist(),
fill_color='lavender',
align='left'))
])
fig.show()
https://thispointer.com/pandas-convert-a-dataframe-into-a-list-of-rows-or-columns-in-python-list-of-lists/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With