i generate a table in python with plotly and i save it as png . but the saved png has a lot of whitespace. i there a solution that the png/or image is "filled" or "Full-screen/image".
i generate the table with:
import plotly.graph_objects as go
fig = go.Figure(data=[go.Table(header=dict(values=['A Scores', 'B Scores']),
cells=dict(values=[[100, 90, 80, 90], [95, 85, 75, 95]]))
])
plotly.io.write_image(fig, file='example_table.png', format='png')
thanks for ideas and solutions. greets alex
Use this code:
import plotly.graph_objects as go
fig = go.Figure(data=[go.Table(header=dict(values=['A Scores', 'B Scores']),
cells=dict(values=[[100, 90, 80, 90], [95, 85, 75, 95]]))
])
fig.update_layout(
autosize=False,
margin = {'l':0,'r':0,'t':0,'b':0},
height = 125
)
fig.write_image("fig1.png")
the update_layout will help you to fix the height and weight of the chart.
Output:
Related
I am using the following nested dictionary to make a lineplot:
df = {'A':
{'weight': [200, 190, 188, 180, 170],
'days_since_gym': [0, 91, 174, 205, 279],
'days_since_fasting': 40},
'B':
{'weight': [181, 175, 172, 165, 150],
'days_since_gym': [43, 171, 241, 273, 300],
'days_since_fasting': 100}}
While making the lineplot, I want the Y-Axis ticks as the percentage value, for which I'm using PercentFormatter:
# set the plot size
fig, ax = plt.subplots(2, figsize=(10, 6))
for i, x in enumerate(df.keys()):
sns.lineplot(
x=df[x]['days_since_gym'],
y=df[x]['weight'],
marker="o",
ax=ax[i],
)
ax[i].axvline(df[x]['days_since_fasting'], color='k', linestyle='--', label='Fasting Starts')
ax[i].set_xlim(left=0, right=365)
# Percentage y-axis
ax[i].yaxis.set_major_formatter(mtick.PercentFormatter())
plt.xlabel('Days Since Joined Gym')
plt.ylabel('Relastive Weight')
plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
plt.show()
However, I don't want the default percentage value (as the fig shows). I want the 1st value would be the starting percentage and the subsequent value would be the relative percentage. For example, the 1st plot starts with 200%, which I want as 0%, and the plot ends with 170%, which I want as -something%.
Any suggestions would be appreciated. Thanks!
One way with minor changes to your code is to make the values in y relative to the first value. That is, keep everything as is and replace:
y=df[x]['weight'],
with:
y=[a-df[x]['weight'][0] for a in df[x]['weight']],
I'm trying to the image shown below and I thought python would be a good idea to do this but I'm not sure. I want to randomize lots of football players' stats, make a radar chart for each and save the charts as images.
But the plotly radar charts are not so stylish and I really want to make something stylish. How to turn the below demo code into the reference image and is it possible?
Here's a demo code:
import plotly.graph_objects as go
categories = ['Defending','Speed','Attacking',
'Technical', 'Team play']
fig = go.Figure()
fig.add_trace(go.Scatterpolar(
r=[1, 5, 2, 2, 3],
theta=categories,
fill='toself',
name='Alice'
))
fig.add_trace(go.Scatterpolar(
r=[4, 3, 2.5, 1, 2],
theta=categories,
fill='toself',
name='Bob'
))
fig.update_layout(
polar=dict(
radialaxis=dict(
visible=True,
range=[0, 5]
)),
showlegend=False
)
fig.show()
From the documentation for polar layout, it seems that Plotly does not offer much options when it comes the grid shape itself. However, Plotly allows you to create your own templates/themes or examine built-in themes.
As a starting point, you should probably analyze the plotly_dark theme as it has some features similar to your picture.
simple example with built-in template
dataset.csv
categories,player,points
Defending,alice,1
Speed,alice,5
Attacking,alice,2
Technical,alice,2
Team play,alice,3
Defending,bob,4
Speed,bob,3
Attacking,bob,2.5
Technical,bob,1
Team play,bob,2
code
import plotly.express as px
import pandas as pd
df = pd.read_csv("dataset.csv")
fig = px.line_polar(df, r="points",
theta="categories",
color="player",
line_close=True,
color_discrete_sequence=["#00eb93", "#4ed2ff"],
template="plotly_dark")
fig.update_polars(angularaxis_showgrid=False,
radialaxis_gridwidth=0,
gridshape='linear',
bgcolor="#494b5a",
radialaxis_showticklabels=False
)
fig.update_layout(paper_bgcolor="#2c2f36")
fig.show()
With the above code I don't think it is possible to modify the color of each nested shape. To be able to do so, you will probably have to create your own template and color each nested shape separately.
creating grid shape
You might have to try something similar the code below to create your desired grid shape.
import plotly.graph_objects as go
bgcolors = ["#353841", "#3f414d", "#494b5a", "#494b5a", "#58596a"]
fig = go.Figure(go.Scatterpolar(
r=[42]*8,
theta=[0, 45, 90, 135, 180, 225, 270, 315],
marker_line_width=2,
opacity=0.8,
marker=dict(color=bgcolors[0])
))
for i in range(1, 5):
fig.add_trace(go.Scatterpolar(
r=[44-6*i]*8,
theta=[0, 45, 90, 135, 180, 225, 270, 315],
marker_line_width=2,
marker=dict(color=bgcolors[i])
))
fig.update_polars(angularaxis_dtick='')
fig.update_traces(fill='toself')
fig.update_polars(angularaxis_showgrid=False,
radialaxis_showgrid=False,
radialaxis_gridwidth=0,
gridshape='linear',
radialaxis_showticklabels=False,
angularaxis_layer='above traces'
)
fig.show()
The colors are off the general shape is good.
I'm building a simple Plotly table with margins as 0 but the output still spits out huge whitespace at the bottom of it. I tried using height to set adjustment but that's static and will not change if the number of rows change in data as recommended here
Code
import plotly.graph_objects as go
layout = go.Layout(
margin=go.layout.Margin(
l=0, #left margin
r=0, #right margin
b=0, #bottom margin
t=0, #top margin
pad=0
)
)
fig = go.Figure(data=[go.Table(header=dict(values=['A Scores', 'B Scores']),
cells=dict(values=[[100, 90, 80, 90], [95, 85, 75, 95]]))
],layout=layout)
fig.show()
Result
How do I get rid of that whitespace?
It is possible to set the graph size to the desired size in both width and height by setting the automatic setting to False.
fig.update_layout(autosize=False,
width=250,
height=120
)
I am looking for a solution to set a vertical border and color for a specific column(s). for this example the column "Scores".
import plotly.graph_objects as go
import plotly
fig = go.Figure(data=[go.Table(
header=dict(values=['<b>Values', '<b>Scores', 'column'],
line_color='darkslategray',
#fill_color='lightskyblue',
align='center'),
cells=dict(values=[[100, 100, 100, 300], # 1st column
[90, 90, 90, 270],
[90, 90, 90, 270]], # 2nd column
line_color='darkslategray',
#fill_color='lightcyan',
align='center'))
])
fig.update_layout(width=250, height=130)
fig.update_layout(margin=dict(l=10, r=10, t=10, b=10))
fig.show()
the perfect solution I expect looks like the table (created with excel). if somebody only know how to color the column this also would help. Thanks!
As far as I know, you cannot change the color of individual ruled lines. The only settings for lines are line width and color. The color for each cell can be specified individually by column or by an array corresponding to the cell.
import plotly.graph_objects as go
import plotly
fig = go.Figure(data=[go.Table(
header=dict(values=['<b>Values', '<b>Scores', 'column'],
line_color=['white','mediumpurple','white'],
fill_color=['white','mediumpurple','white'],
align='center'),
cells=dict(values=[[100, 100, 100, 300], # 1st column
[90, 90, 90, 270],
[90, 90, 90, 270]], # 2nd column
line_color=['white','mediumpurple','white'],
fill_color=['white','mediumpurple','white'],
align='center'))
])
fig.update_layout(width=250, height=130)
fig.update_layout(margin=dict(l=10, r=10, t=10, b=10))
fig.show()
I have a DataFrame and I can save it as a png file. But now I want to change the background color of specific cells who meet a certain condition.
Conditions:
Numbers who are 80 or higher must get a green background.
Numbers below 80 must get a red background.
All column names and index cells need a black background with a white text color.
The following posts came close to what I want but didn't provided with the answer I needed.
Post 1
Post 2
My code:
import matplotlib.pyplot as plt
from pandas.tools.plotting import table
import pandas as pd
#My dataframe
df = pd.DataFrame({
'Weeks' : [201605, 201606, 201607, 201608],
'Computer1' : [50, 77, 96, 100],
'Computer2' : [50, 79, 100, 80],
'Laptop1' : [75, 77, 96, 95],
'Laptop2' : [86, 77, 96, 40],
'Phone' : [99, 99, 44, 85],
'Phone2' : [93, 77, 96, 25],
'Phone3' : [94, 91, 96, 33]
})
df2 = df.set_index('Weeks') #Makes the column 'Weeks' the index.
#Make a png file out of an dataframe.
plt.figure(figsize=(9,3))
ax = plt.subplot(211, frame_on=False) # no visible frame
ax.xaxis.set_visible(False) # hide the x axis
ax.yaxis.set_visible(False) # hide the y axis
table(ax, df2, rowLabels=df2.index, colLabels=df2.columns, loc='center', cellColours=None)
plt.savefig('mytable.png') #save it as an png.
This is how it currently looks:
This is how I want it to look
you can do something like this:
colors = df2.applymap(lambda x: 'green' if x>= 80 else 'red').reset_index().drop(['Weeks'], axis=1)
tbl = table(ax, df2, loc='center',
cellColours=colors.as_matrix(),
colColours=['black']*len(colors.columns),
rowColours=['black']*len(colors))
Setting index's color:
[tbl._cells[row, -1]._text.set_color('white') for row in range(1, len(colors)+1)]
setting header's colors:
[tbl._cells[0, col]._text.set_color('white') for col in range(len(colors.columns))]
plt.show()
Code (complete):
import matplotlib.pyplot as plt
from pandas.tools.plotting import table
import pandas as pd
#My dataframe
df = pd.DataFrame({
'Weeks' : [201605, 201606, 201607, 201608],
'Computer1' : [50, 77, 96, 100],
'Computer2' : [50, 79, 100, 80],
'Laptop1' : [75, 77, 96, 95],
'Laptop2' : [86, 77, 96, 40],
'Phone' : [99, 99, 44, 85],
'Phone2' : [93, 77, 96, 25],
'Phone3' : [94, 91, 96, 33]
})
df2 = df.set_index('Weeks') #Makes the column 'Weeks' the index.
colors = df2.applymap(lambda x: 'green' if x>= 80 else 'red') \
.reset_index().drop(['Weeks'], axis=1)
#print(colors)
plt.figure(figsize=(10,5))
ax = plt.subplot(2, 1, 1, frame_on=True) # no visible frame
#ax.xaxis.set_visible(False) # hide the x axis
#ax.yaxis.set_visible(False) # hide the y axis
# hide all axises
ax.axis('off')
# http://matplotlib.org/api/pyplot_api.html?highlight=table#matplotlib.pyplot.table
tbl = table(ax, df2,
loc='center',
cellLoc='center',
cellColours=colors.as_matrix(),
colColours=['black']*len(colors.columns),
rowColours=['black']*len(colors),
#fontsize=14
)
# set color for index (X, -1) and headers (0, X)
for key, cell in tbl.get_celld().items():
if key[1] == -1 or key[0] == 0:
cell._text.set_color('white')
# remove grid lines
cell.set_linewidth(0)
# refresh table
plt.show()
# save it as an png.
plt.savefig('mytable.png')