Fitzgerald
Fitzgerald

Reputation: 41

How do I save a graph and a table to one file(PDF, JPG, PNG, etc) from Jupyter Notebook so that the table is next(on the right) to the graph?

I have taken the utility bill and decided to run it through Jupyter Notebook for fun.

This is what I imported in the first cell:

import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import chart_studio.plotly as py
import plotly.figure_factory as ff

There are two dataframes: cost_annually and and cost_annually_for_table.

list_of_annual_cost = [costfor14, costfor15, costfor16, costfor17, costfor18, costfor19, costfor20, costfor21, costfor22]
final_annual_cost = []
for i in list_of_annual_cost:
    new = (i/total_cost)* 100
    final_annual_cost.append(round(new, 2))
# dictionary with list object in values
annual_cost = {
    'Years' : ["2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022"],
    'Cost': [costfor14, costfor15, costfor16, costfor17, costfor18, costfor19, costfor20, costfor21, costfor22],
    'Total Cost': total_cost,
    '% of TC': final_annual_cost
            }
  
# creating a Dataframe object 
cost_annually = pd.DataFrame(annual_cost)
cost_annually

sidebar: costfor16, costfor17, etc are variables from earlier cells in the code representing the total cost for the years 2016, 2017, etc

The latter is a copy of the former, where cost_annually_for_table had its numeric columns converted to strings so I could add the dollar signs back and remove trailing zeros- it's for presentation.

Cost_annually is for all of the fun stuff so the datatypes for cost and total cost columns are floats.

This cell is where I am a bit befuddled:

ax1 = cost_annually.plot.bar(x='Years', y="Cost", rot=45);
fig =  ff.create_table(cost_annually_for_table)
fig.update_layout(
    autosize=False,
    width=500,
    height=200,
)
fig.write_image("table_plotly.png", scale=2)
fig.show()

The first line is the bar graph and everything else is for the table. However, the table is run first and then the bar graph...so the table is on top of the bar graph.

I removed the first line and added it as the last line of code but the table is still on top of the bar graph.

How do I put the table next to the graph(on the right of the graph) from Jupyter Notebook and save these two images in one file?

I appreciate your time.

This is the sample data from 2014 enter image description here

This is how it looks in the Jupyter Cell:

enter image description here enter image description here

Upvotes: 2

Views: 1007

Answers (1)

Baron Legendre
Baron Legendre

Reputation: 2188

df
###
   Years     Cost  Total Cost  % of TC
0   2014  3247.85    26949.14   0.1205
1   2015  3018.08    26949.14   0.1120
2   2016  3084.52    26949.14   0.1145
3   2017  2768.78    26949.14   0.1027
4   2018  3421.73    26949.14   0.1270
5   2019  2893.52    26949.14   0.1074
6   2020  2986.25    26949.14   0.1108
7   2021  3280.47    26949.14   0.1217
8   2022  2247.94    26949.14   0.0834
df_plot = df[['Years','Cost']].copy()
df_table = df.copy()
df_table['Cost'] = df_table['Cost'].apply(lambda x: "${:}".format(x))
df_table['Total Cost'] = df_table['Total Cost'].apply(lambda x: "${:}".format(x))
df_table['% of TC'] = (df_table['% of TC']).apply(lambda x: "{:.2%}".format(x))
# table
fig = ff.create_table(df_table)

# plot
# Unmark if we want color variate with 'Cost'
# fig.add_trace(go.Bar(x=df_plot['Years'], y=df_plot['Cost'], xaxis='x2', yaxis='y2', name='Cost', marker_color=df_plot['Cost']))
fig.add_trace(go.Bar(x=df_plot['Years'], y=df_plot['Cost'], xaxis='x2', yaxis='y2', name='Cost', marker_color='#41bf9b'))
fig.update_layout(title='Cost Annually',
                  height=600,
                  margin = {'l': 5, 'r': 5, 't': 100, 'b': 2},
                  xaxis = {'domain':[0, 0.45]},
                  xaxis2 = {'domain':[0.55, 1]},
                  yaxis2 = {'anchor':'x2'}
                  )
fig.show()

enter image description here The graph includes two-part Table and Barchart, you only need to specify domain to arrange the layout. axis are floating area in a fixed canvas, adjust their size via domain.




# table
fig2 = ff.create_table(df_table)

# plot
fig2.add_trace(
    go.Bar(x=df_plot['Years'], y=df_plot['Cost'], xaxis='x2', yaxis='y2', name='Cost', marker_color='#41bf9b'))
fig2.update_layout(title='Cost Annually',
                   height=600,
                   margin={'l': 5, 'r': 5, 't': 100, 'b': 2},
                   xaxis={'domain': [0.55, 1]},
                   xaxis2={'domain': [0, 0.45]},
                   yaxis2={'anchor': 'x2'}
                   )
fig2.show()

enter image description here

Upvotes: 1

Related Questions