Attach format to a pie chart xlsxwriter Python - python

have a pie chart defined here:
chart_1 = workbook.add_chart({'type': 'pie'})
chart_1.add_series({
'name': 'Pie data',
'categories': '=Sheet2!$A$1:$A$' + str(len(cat_count)),
'values': '=Sheet2!$B$1:$B$' + str(len(cat_count)),
'data_labels': {'value': True, 'leader_lines': True, 'name': 'georgia',
'font': {'size': 25, 'color': 'white', 'bold': True}},
})
I am trying to add some formatting , particularly a 'gerogia' font to the categories so they are uniform with the rest of my file

You almost had the syntax correct apart from needing to set the name as part of the font sub-properties.
Here is a small working example:
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_pie.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write_column('A2', ['Apple', 'Cherry', 'Pecan'])
worksheet.write_column('B2', [30, 30, 30])
chart = workbook.add_chart({'type': 'pie'})
chart.add_series({
'name': 'Pie data',
'categories': ['Sheet1', 1, 0, 3, 0],
'values': ['Sheet1', 1, 1, 3, 1],
'data_labels': {'value': True,
'leader_lines': True,
'font': {'size': 25,
'name': 'georgia',
'color': 'white',
'bold': True}},
})
chart.set_legend({'font': {'name': 'georgia'}})
worksheet.insert_chart('C2', chart, {'x_offset': 25, 'y_offset': 10})
workbook.close()
Output:
Note also the somewhat easier programatic way of setting the range for the categories and values.

Related

Add a vertical line in XLXSWriter graph

I need to add a vertical line to the excel chart similar to below image. The chart is developed using Xlsxwriter==1.2.9.
I am trying to pass a single value (passing a single cell range) to the values field and removed the categories tab.
chart.add_series({'name': 'Vertical Line',
                  'values':f"{sheet_name,2,5,2,5}",
                  'line': {'width': 2.5, 'dash_type': 'dash', 'color': '#9ED8D2'}})
Please advice.
Picture reference:
https://www.officetooltips.com/excel_2016/tips/how_to_add_a_vertical_line_to_the_chart.html
The following code will duplicate the example from 'how_to_add_a_vertical_line_to_the_chart.html' fairly close.
When the date is changed in cell 'D4' the vertical line will move to the corresponding date on the x-axis.
import xlsxwriter
workbook = xlsxwriter.Workbook('xlsxwriter_vline_chart.xlsx')
worksheet = workbook.add_worksheet()
### Add the worksheet data to be plotted.
### Set column widths
worksheet.set_column(1, 3, 12)
### Common format
common_format = workbook.add_format({
'border': 1,
})
### Add Headers
Header_data = ['', 'Day', 'New Sales']
cformat = workbook.add_format({
'bold': True,
'bg_color': '#92D050',
'border': 1,
})
worksheet.write_row('B5', Header_data, cformat)
### ID Column
id_data = list(range(1,16))
worksheet.write_column('B6', id_data, common_format)
### Day Column
dates_format = workbook.add_format({
'num_format': 'd-mmm-yy',
'border': 1,
})
dates_data = list(range(44774, 44789))
worksheet.write_column('C6', dates_data, dates_format)
### Values Column
values_data = [132, 128, 95, 115, 83, 87, 67, 97, 112, 84, 77, 97, 86, 77, 83]
worksheet.write_column('D6', values_data, common_format)
### Add Date for Vertical line position
vh_format = workbook.add_format({
'bold': True,
'border': 1,
})
worksheet.write('C4', 'Vert line Date', vh_format)
vd_format = workbook.add_format({
'bold': True,
'num_format': 'd-mmm-yy',
'font_color': 'red'
})
worksheet.write('D4', 44780, vd_format)
### Create a new chart object [Line Chart].
chart_name = 'Chart Test'
chart = workbook.add_chart({'type': 'line'})
chart.add_series({
'name': 'Data',
'values': '=Sheet1!$D$6:$D$20',
'categories': '=Sheet1!$C$6:$C$20',
'smooth': True,
})
### Add 2nd series for the Vertical Line [Scatter Chart]
scatter_series = workbook.add_chart({'type': 'scatter'})
### Set vertical line chart data and format
scatter_series.add_series({
'name': 'VerticalLine',
'categories': '=Sheet1!$D$4',
'values': '=Sheet1!$D$6:$D$20',
'marker': {'type': 'none'},
'line': {'color': 'red',
'width': 1.5,
},
'y_error_bars': {
'type': 'fixed',
'value': 80,
'direction': 'minus',
'line': {'color': 'red',
'width': 1.5,
'dash_type': 'dash',
}
},
})
# # Combine both Line and Scatter charts
chart.combine(scatter_series)
### Chart customisation
chart.set_title({'name': 'Line Chart with Dynamic Vertical line'})
chart.set_size({'width': 580})
chart.set_x_axis({
'name': 'Day',
'date_axis': True,
'minor_unit': 1,
'minor_unit_type': 'days',
'major_unit': 2,
'major_unit_type': 'days',
})
chart.set_y_axis({
'name': 'New Sales',
'min': 60,
'max': 140,
})
# Insert the chart into the worksheet.
worksheet.insert_chart('F6', chart, {'x_scale': 2, 'y_scale': 1})
workbook.close()

Can plotly(python) slider start static (without animation) in html file?

I have been trying to create a plotly figure (scatter plot) with a date slider and then exporting the figure to an HTML file.
To do so I have used the plotly px library: px.scatter(animation_frame...), just as in the second example here: https://plotly.com/python/sliders/.
Once I have the figure I save it to a HTML file with fig.to_html(full_html=False, include_plotlyjs='cdn').
This does work, but the problem I face is that the slider starts animating the frames by default whenever I open the html file. Is there a way to make the slider start static by default? I need it to start static because the figure has many frames and the slider automatically updating the frames makes the file really slow.
My code is:
figDVTO = px.scatter(dfPrueba, x="DíasVencimiento", y="Inflación", labels=dict(DíasVencimiento="Días al Vencimiento", Inflación="Inflación Implícita (%)"),
animation_frame="Fecha", title="Curva Inflación Implícita Diaria", range_y=[1, 8],
range_x=[0,7000], color = "Implícita", color_discrete_map = dicColores)
figDVTO.update_traces(marker=dict(size=12, line=dict(width=2,
color='DarkSlateGrey')),
selector=dict(mode='markers'))
I tried to set the "stop" animation button as default, but even when I do so, the slider animates the frames.
I also tried to construct the figure with plotly.graph_objects Figure, by constructing the dictionary that contains the frames.
I am able to recreate the figure I create with plotly express. However, after looking in plotly´s documentation I´m still no sure how to make the slider initially static. Have tried changing the method in updatemenus, as well as changing the method in sliders, but nothing seems to work.
I would really appreciate any sort of help, been scratching my head for weeks now...
Here is my complete code to construct the figure with plotly.graph_objects:
# make figure
fig_dict = {
"data": [],
"frames": [],
"layout": {'legend': {'title': {'text': 'Implícita'}, 'tracegroupgap': 0},
'sliders': [{
'active': 0,
'currentvalue': {'prefix': 'Fecha='},
'len': 0.9,
'pad': {'b': 10, 't': 60},
'steps':[],
'x': 0.1,
'xanchor': 'left',
'y': 0,
'yanchor': 'top'
}],
'title': {'text': 'Curva Inflación Implícita Diaria',
'font':dict(
family="Arial",
size=18,
)
},
'updatemenus': [{'active': 0,
'bgcolor': '#B0BEC5',
'buttons': [{'args': [None, {'frame': {'duration':
500, 'redraw': False},
'mode': 'immediate',
'fromcurrent': True,
'transition': {'duration':
500, 'easing': 'linear'}}],
'label': '▶',
'method': 'animate'},
{'args': [[None], {'frame':
{'duration': 0, 'redraw':
False}, 'mode': 'immediate',
'fromcurrent': True,
'transition': {'duration': 0,
'easing': 'linear'}}],
'label': '◼',
'method': 'animate'}],
'direction': 'left',
'pad': {'r': 10, 't': 70},
'showactive': True,
'type': 'buttons',
'x': 0.1,
'xanchor': 'right',
'y': 0,
'yanchor': 'top'}],
'xaxis': {'anchor': 'y',
'domain': [0.0, 1.0],
'range': [0, 7000],
'title': {'text': 'Días al Vencimiento'}},
'yaxis': {'anchor': 'x',
'domain': [0.0, 1.0],
'range': [1, 8],
'title': {'text': 'Inflación Implícita (%)'}}
}
}
#Creating starting frame
listFechas = list(dfPrueba['Fecha'].unique())
listImplicitas = list(dfPrueba['Implícita'].unique())
fecha=listFechas[0]
for implicita in listImplicitas:
data_dict = {
"x": np.array(dfPrueba.loc[(dfPrueba['Fecha']==fecha)&(dfPrueba['Implícita']==implicita), 'DíasVencimiento']),
"y": np.array(dfPrueba.loc[(dfPrueba['Fecha']==fecha)&(dfPrueba['Implícita']==implicita), 'Inflación']),
'legendgroup': str(implicita),
'hovertemplate': ('Implícita='+ str(implicita)+'<br>Fecha='+str(fecha)+'<br>Días al Vencimiento=%{x}<br>Inflación Implícita (%)=%{y}<extra></extra>'),
'marker': {'color': dicColores[implicita], 'line': {'color': 'DarkSlateGrey', 'width': 2}, 'size': 12, 'symbol': 'circle'},
"mode": "markers",
'marker': {'color': dicColores[implicita], 'line': {'color': 'DarkSlateGrey', 'width': 2}, 'size': 12, 'symbol': 'circle'},
"name": str(implicita),
'orientation': 'v',
'showlegend': True,
'type': 'scatter',
'xaxis': 'x',
'yaxis': 'y',
}
fig_dict["data"].append(data_dict)
# make frames
for fecha in listFechas:
frame = {"data": [], "name": str(fecha)}
for implicita in listImplicitas:
data_dict = {
"x": np.array(dfPrueba.loc[(dfPrueba['Fecha']==fecha)&(dfPrueba['Implícita']==implicita), 'DíasVencimiento']),
"y": np.array(dfPrueba.loc[(dfPrueba['Fecha']==fecha)&(dfPrueba['Implícita']==implicita), 'Inflación']),
'legendgroup': str(implicita),
'hovertemplate': ('Implícita='+ str(implicita)+'<br>Fecha='+str(fecha)+'<br>Días al Vencimiento=%{x}<br>Inflación Implícita (%)=%{y}<extra></extra>'),
'marker': {'color': dicColores[implicita], 'line': {'color': 'DarkSlateGrey', 'width': 2}, 'size': 12, 'symbol': 'circle'},
"mode": "markers",
'marker': {'color': dicColores[implicita], 'line': {'color': 'DarkSlateGrey', 'width': 2}, 'size': 12, 'symbol': 'circle'},
"name": str(implicita),
'orientation': 'v',
'legendgroup': '23',
'showlegend': True,
'type': 'scatter',
'xaxis': 'x',
'yaxis': 'y'
}
frame["data"].append(data_dict)
fig_dict["frames"].append(frame)
#Updating sliders steps
for fecha in listFechas:
loop_dic={'args': [[str(fecha)], {'frame':
{'duration': 0, 'redraw': False},
'mode': 'immediate', 'fromcurrent':
True, 'transition': {'duration': 0,
'easing': 'linear'}}],
'label': str(fecha),
'method': 'animate'}
fig_dict["layout"]["sliders"][0]["steps"].append(loop_dic)
#Creating figure
figB = go.Figure(fig_dict)
figB.update_layout(
title="Curva Inflación Implícita Diaria",
xaxis_title="Días al Vencimiento",
yaxis_title="Inflación Implícita (%)",
legend_title="Serie",
font=dict(
family="Arial",
size=18,
),
hovermode="x",
yaxis=dict(tickformat=".2f")
)

Unable to combine line and two scatter plots in xlsxwriter. Also having problems coloring plot symbols

I am trying to create a spreadsheet plot with a line and two scatter charts. I am trying to have different symbols for each scatter chart:
# create the chart and add it to the workbook:
value_line_chart = workbook.add_chart({'type': 'line'})
value_line_chart.set_y_axis({'name': 'Values'})
value_line_chart.set_x_axis({'name': 'Time'})
value_line_chart.set_title({'name': 'Chart of {}'.format(historical_data.symbol)})
value_line_chart.add_series({
'line': {
'color': 'cyan',
'width': .5
},
'values': [worksheet.name, data_start_row, value_col, last_col, value_col],
'categories': [worksheet.name, data_start_row, date_col, last_col, date_col],
'name': "data",
})
scatter_buy_chart = workbook.add_chart({'type': 'scatter'})
scatter_buy_chart.add_series({
'marker': {
'type': 'long_dash',
'size': 5,
'border': {'color': 'red'},
'fill': {'color': 'red'},
},
'values': [worksheet.name, data_start_row, buy_action_col, last_col, buy_action_col],
'categories': [worksheet.name, data_start_row, date_col, last_col, date_col],
'name': "buy",
})
value_line_chart.combine(scatter_buy_chart)
scatter_sell_chart = workbook.add_chart({'type': 'scatter'})
scatter_sell_chart.add_series({
'marker': {
'type': 'plus',
'size': 5,
'border': {'color': 'green'},
'fill': {'color': 'green'},
},
'values': [worksheet.name, data_start_row, sell_action_col, last_col, sell_action_col],
'categories': [worksheet.name, data_start_row, date_col, last_col, date_col],
'name': "buy",
})
value_line_chart.combine(scatter_sell_chart)
value_line_chart.set_size({'width': 720, 'height': 576})
value_line_chart.set_x_axis({
'date_axis': True,
'min': date_data[0],
'max': date_data[len(date_data)-1]
})
value_line_chart.set_legend({'none': True})
worksheet.insert_chart('B1', value_line_chart)
workbook.close()
The problems that I am having are:
I am unable to get the second scatter chart to show up
I am unable to get the colors of the symbols to change
I have tried rendering the line and scatter charts individually and the the data and symbol shapes show up correctly.
I am able to change the color of the line chart.
I am able to change the shape of the symbols.
I am able to render the line chart and only one of the two scatter charts.
I was able to get the results I was looking for by adding all of the series into the single chart:
# create the chart and add it to the workbook:
chart = workbook.add_chart({'type': 'line'})
chart.set_y_axis({'name': 'Values'})
chart.set_x_axis({'name': 'Time'})
chart.set_title({'name': 'Chart of {}'.format(historical_data.symbol)})
chart.add_series({
'line': {
'color': 'cyan',
'width': .5
},
'values': [worksheet.name, data_start_row, value_col, last_col, value_col],
'categories': [worksheet.name, data_start_row, date_col, last_col, date_col],
'name': "data",
})
chart.add_series({
'marker': {
'type': 'long_dash',
'size': 8,
'border': {'color': 'red'},
'fill': {'color': 'red'},
},
'values': [worksheet.name, data_start_row, buy_action_col, last_col, buy_action_col],
'categories': [worksheet.name, data_start_row, date_col, last_col, date_col],
'name': "buy",
})
chart.add_series({
'marker': {
'type': 'plus',
'size': 8,
'border': {'color': 'green'},
'fill': {'color': 'green'},
},
'values': [worksheet.name, data_start_row, sell_action_col, last_col, sell_action_col],
'categories': [worksheet.name, data_start_row, date_col, last_col, date_col],
'name': "buy",
})
chart.set_size({'width': 720, 'height': 576})
chart.set_x_axis({
'date_axis': True,
'min': date_data[0],
'max': date_data[len(date_data)-1]
})
chart.set_legend({'none': True})
worksheet.insert_chart('B1', chart)
workbook.close()
It isn’t possible to combine more than 2 charts with XlsxWriter. That is a limitation of the library.

Formating Plotly Guage Text

I have some data I'm putting on a Plotly gauge. Not sure how I managed to get a rounded number but I'd like the complete and acurate value to displayed in the text instead of just 1k, for instance my data should now say $1,001.50 but it instead says 1k.
Not too worried about the "ticks" using the k, just the text.
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Indicator(
domain = {'row': 1, 'column': 0},
value = 1001.50,
mode = "gauge+number",
title = {'text': "Total Donations"},
delta = {'reference': 46000},
gauge = {'axis': {'range': [None, 46000]},
'threshold' : {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 40000
}}))
fig.add_trace(go.Indicator(
mode = "number+delta",
value = 540,
number = {'prefix': "$"},
delta = {'position': "top", 'reference': 450},
domain = {'row': 1, 'column': 1}))
fig.update_layout(
grid = {'rows': 1, 'columns': 2, 'pattern': "independent"},
template = {'data' : {'indicator': [{
'title': {'text': "Donations this Month"},
'mode' : "number+delta+gauge",
'delta' : {'reference': 90}}]
}})
Select General for the number formatting. See here.
fig.add_trace(go.Indicator(
domain = {'row': 1, 'column': 0},
value = 1001.50,
mode = "gauge+number",
number = {'valueformat':"g"},
title = {'text': "Total Donations"},
delta = {'reference': 46000},
gauge = {'axis': {'range': [None, 46000]},
'threshold' : {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': 40000}}))

remove points from excel file line chart using python package xlsxwriter

I have this chart, created using python package xlsxwriter and I wanna remove all the points in the middle and only keep the first one and last one.
before :
Final results wanted.:
I tried the attribute points but unfortunate, it didn't work for me.
line_chart.add_series(
{
'values': '='+worksheet_name+'!$C$'+str(row_range+1)+':$I'+str(row_range+1),
'marker': {'type': 'diamond'},
'data_labels': {'value': True, 'category': True, 'position': 'center', 'leader_lines': True},
'points': [
{'fill': {'color': 'green'}},
None,
None,
None,
None,
None,
{'fill': {'color': 'red'}}
],
'trendline': {
'type': 'polynomial',
'name': 'My trend name',
'order': 2,
'forward': 0.5,
'backward': 0.5,
'line': {
'color': 'red',
'width': 1,
'dash_type': 'long_dash'
}
}
}
)
I also tried:
line_chart.set_x_axis({
'major_gridlines': {'visible': False},
'minor_gridlines': {'visible': False}
'delete_series': [1, 6]
})
no luck.
Anobody can help me please?
Thanks in advance!

Categories

Resources