xlsxwriter: How to change scatter chart subtype for single add_series()? - xlsxwriter

I define a scatter chart using subtype smooth and add some data:
chart1 = workbook.add_chart({'type': 'scatter', 'subtype' : 'smooth'})
Sname = "=Measurement_dBV!%s1" %(row_list[i])
chart.add_series({
'name': Sname,
'categories': ['Measurement_dBV',1,0,numData,0],
'values': ['Measurement_dBV',1,i+1,numData,i+1],
'line': {'width': 1.0, 'color': color_list[i]},
})
This works fine. But now I need to add two other data lines to the same chart but in this case the lines must be a subtype of straight.
My first idea was to use "combine". But the documentation say, that a chart of type scatter can´t be the primary chart as well as the combined chart is the same type.
So: How to change the subtype for a single data series?
In Excel you can define different types of charts an it´s subtypes for every single data series.
Thanks for any help or suggestions.
Best Regards
Karsten

In XlsxWriter if your chart subtype is smooth then you can turn it off for an individual series using the smooth chart option:
# Add a smooth scatter chart.
chart = workbook.add_chart({
'type': 'scatter',
'subtype': 'smooth'
})
# Add a series with default smooth.
chart.add_series({
'categories': '=Sheet1!$A$1:$A$5',
'values': '=Sheet1!$B$1:$B$5',
})
# Add a series with smooth turned off.
chart.add_series({
'categories': '=Sheet1!$A$1:$A$5',
'values': '=Sheet1!$C$1:$C$5',
'smooth': False,
})

Thanks a lot!
Simple as it is, but you have to know it...
GREAT!
regards
Karsten

Related

How to add drop down to my line chart in dash based on a column in dataframe?

I have cleaned the dataframe and plotting these graphs on plotly and work fine on Dash. I want to insert a dropdown for x-axis (i.e, Y and P for both the graphs separately). I am trying with dcc.dropdown but it's not working.
I have been trying with this but am confused about the dcc dropdown. Any help would be appreciated, I am new to Dash!
fig1 = px.line(df_1, x='Y',y=['x','y'])
fig2 = px.line( df_2, x='P',y=['x','y'])
app.layout = html.Div(children=[
# All elements from the top of the page
html.Div([
html.H1(children='...'),
html.Div(children='''
'''
'''),
dcc.Graph(
id='graph1',
figure=fig1
),
]),
# New Div for all elements in the new 'row' of the page
html.Div([
html.H1(children=''),
html.Div(children='''
'''),
dcc.Graph(
id='graph2',
figure=fig2
),
]),
])
if __name__ == '__main__':
app.run_server(debug=True, use_reloader = False)
It is all here https://dash.plotly.com/dash-core-components/dropdown.
Make sure you use dcc.Dropdown instead of dcc.dropdown (lowercase)

geoscatter plot on plotly with a shape file

I need to plot Italy's map with points on it, using plotly and dash libraries.
Actually, I've done that using go.scattergeo. But it does not show the borders of provinces. (Generally the quality of map is less than shape file that I have)
I also succeed to plot shape file with scatter points in matplotlib. But I have to plot it in plotly to use in my dashboard.
Is there any way to have a scatter plot with a shape file in plotly?
To have Ideas what's the target I post the photos:
This is my dash:
enter image description here
This is shape file with scatter plots on matplotlib:
enter image description here
I believe that you should convert your shapefile to a geojson format, or just download a geojson-file with your desired resolution.
You could then use go.Scattermapbox to plot your scatter-plot over the map from your geojson-file. I downloaded a geojson-file from github for the example below (such that it should work if you run the code).
The image from my example code ends up looking like this:
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/openpolis/geojson-italy/master/geojson/limits_IT_regions.geojson') as response:
counties = json.load(response)
import plotly.graph_objects as go
fig = go.Figure(go.Scattermapbox(
mode = "markers",
lon = [12.5], lat = [41.9],
marker = {'size': 5, 'color': ["red"]}))
fig.update_layout(
mapbox = {
'style': "white-bg",
'center': { 'lon': 12.5, 'lat': 41.9},
'zoom': 4, 'layers': [{
'source': counties,
'type':'fill', 'below':'traces','color': 'grey', 'opacity' : 0.2}],
},
margin = {'l':0, 'r':0, 'b':0, 't':0})
fig.show()

Plotting subdivided bar graph from a dataframe

I have a Dataframe as given below
df = pd.DataFrame(
{
'Dates': ['2021-04-11', '2021-06-08', '2021-06-08', '2021-06-09', '2021-06-10', '2021-07-18', '2021-07-18'],
'Results': ['Negative', 'Invalid', 'Negative','Negative','Negative', 'Negative', 'Positive' ],
'Size': [1, 1, 1, 1, 4, 21, 2]
})
I want to plot a subdivided bar graph as shown below in the given picture.
[![enter image description here][1]][1]
I have been stuck on this for a while now. Tried using groupby(), sum(), size() etc, but could not figure it.
Any help is greatly appreciated.
Thanks.
[1]: https://i.stack.imgur.com/HrKRY.jpg
Just reshape it by setting indices on date and results, then unstacking Results. After that, plot.
df.set_index(['Dates', 'Results']).sort_index(0).unstack().plot.bar(stacked=True)
If you don't want it with a column multi-index, and instead want "Invalid", "Negative", "Positive", just create an intermediate data frame from the unstack (I'll call it temp) and assign temp.columns = temp.columns.get_level_values(1). Then call temp.plot.bar(stacked=True).
To specify size using the OOP matplotlib interface:
f, ax = plt.subplots(figsize=(HEIGHT, WIDTH))
temp.plot.bar(ax=ax, stacked=True)
Save the figure to file using f.savefig(PATH).

Labels alignmnet pie chart / matplotlib 2.1.0+

I am having a question regarding a pie-chart labels alignment.
I'd like to have labels outside the pie-chart and centered to each wedge.
According to the documentation page, "labeldistance" parameter enables to place labels outside the pie-chart, and "ha" & "va" parameters supposed to center. However, these two options (ha & va) seems not working on Matplotlib v2.1.0+.
1) With this example (pls see below), you can see that "car" label is not centered properly, it is a bit off the center.
import matplotlib.pyplot as plt
figure = plt.figure()
axes = figure.add_subplot(111)
axes.set_aspect(1) # circular pie
y = [1,2,3, 4,8,16,18]
label = ['car','domino', 'romancical','testing1', 'thisisthelonglabel',
'fffffffffffffffffffffffffffffffffffffffffff', 'as']
wedges, texts = plt.pie(y,
radius=1.2,
labels=label,
labeldistance=1.0,
rotatelabels =True,
startangle = 10,
wedgeprops = {"linewidth": 0.7,
"edgecolor": "white"},
textprops = dict(ha="center",
va="center")) # doesn't work
plt.show()
I added the following lines to force labels to be centered, which works but disabled "labeldistance" parameter. So all my centered correctly, as I want labels are overlapping with the pie-chart circle.
wedges, texts = plt.pie(y,
radius=1.2,
labels=label,
labeldistance=1.0,
rotatelabels =True,
startangle = 10,
wedgeprops = {"linewidth": 0.7,
"edgecolor": "white"},
textprops = dict(ha="center",
va="center"))
for t in texts:
t.set_horizontalalignment("center")
t.set_verticalalignment("center")
plt.show()
So my question is, do "ha" & "va" options work for other users?
And could anyone advice if there is a solution for keeping "labeldistance" while using .set_horizontalalignment("center") and set_verticalalignment("center") ?
Thank you.
In matplotlib 3.0.2 as well as 2.1.2, using
textprops = dict(va="center", rotation_mode = 'anchor')
(and labeldistance=1.05) results in
Note that this leaves out the ha="center" option, because the horizontal alignment is best be automatically set depending on if the label is on the left or right side of the circle.
For an explanation of rotation_mode see e.g. this question or this question.

xlsxwriter: modifying parts of a line in a scatter chart

in the Python package xlsxwriter, is it possible to format a part of a scatter chart series differently than another part? for example, a scatter chart where some sections of the line of a specific series are blue, and other sections of the same line are red. it is certainly possible in Excel itself by modifying specific data points.
I tried using the 'points' option in many combinations without success. I don't know which options are valid for it in a scatter chart.
UPDATE:
here is an example of what I'm trying to achieve. This was created directly in Excel, not through xlsxwriter. Notice how one section of the line is dashed and red, and another is a different thickness. To create it, simply select a data point and use the options in the sidebar to adjust formatting.
I've made an example that I think answers your question.
I'm using Python 3.5 and xlsxwriter 0.9.6.
In chart 1, I changed the color of the markers based on whether they were in a particular group. It's fairly straightforward if chart 1 is what you're looking for.
In chart 2, I show how to hard code a continuous line with different colors (there may be a better way to do this).
import xlsxwriter
import numpy as np
import pandas as pd
dates = pd.DataFrame({'excel_date':pd.date_range('1/1/2016', periods=12, freq='M')})
dates.excel_date = dates.excel_date - pd.datetime(1899, 12, 31)
data = np.array([11,20,25,35,40,48,44,31,25,38,49,60])
selection = np.array([4,5,6,8,11])
#Creating a list - you could hard code these lines if you prefer depending on the size of your series
diff_color_list = list()
for n in range(1, 13):
if n in selection:
diff_color_list.append({'fill':{'color': 'blue', 'width': 3.25}},)
else:
diff_color_list.append({'fill':{'color': 'red', 'width': 3.25}},)
#Workbook Creation
workbook = xlsxwriter.Workbook("test.xlsx")
format = workbook.add_format({'num_format':'mmm-yy'})
worksheet1 = workbook.add_worksheet("testsheet")
worksheet1.write('A1', 'Date')
worksheet1.write('B1', 'Data')
worksheet1.write_column('A2', dates.excel_date, format)
worksheet1.write_column('B2', data)
chart1 = workbook.add_chart({'type': 'scatter'})
# Configure the series.
chart1.add_series({'categories': '=testsheet!$A$2:$A$13',
'values': '=testsheet!$B$2:$B$13',
'points': diff_color_list
})
chart1.set_title ({'name': 'Results'})
chart1.set_x_axis({'name': 'Date'})
chart1.set_y_axis({'name': 'Data'})
chart1.set_legend({'none': True})
# Second chart with alternating line colors
chart2 = workbook.add_chart({'type': 'scatter',
'subtype': 'straight'})
chart2.add_series({'categories': '=testsheet!$A$2:$A$3',
'values': '=testsheet!$B$2:$B$3',
'line':{'color': 'blue'}
})
chart2.add_series({'categories': '=testsheet!$A$3:$A$4',
'values': '=testsheet!$B$3:$B$4',
'line':{'color': 'red'}
})
chart2.add_series({'categories': '=testsheet!$A$4:$A$5',
'values': '=testsheet!$B$4:$B$5',
'line':{'color': 'blue'}
})
chart2.set_title ({'name': 'Results'})
chart2.set_x_axis({'name': 'Date'})
chart2.set_y_axis({'name': 'Data'})
chart2.set_legend({'none': True})
worksheet1.insert_chart('D6', chart1)
worksheet1.insert_chart('L6', chart2)
workbook.close()
The question is a little bit confusing since you talk about changing the color of parts of a line but also about points.
I'm going to assume you are referring to changing the color of points/markers since as far as I know changing the color of line segments in a series isn't possible in Excel.
Anyway, it it possible to change marker colors in a scatter chart using XlsxWriter. For example:
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_scatter.xlsx')
worksheet = workbook.add_worksheet()
# Add the worksheet data that the charts will refer to.
worksheet.write_column('A1', [1, 2, 3, 4, 5, 6])
worksheet.write_column('B1', [15, 40, 50, 20, 10, 50])
# Create a new scatter chart.
chart = workbook.add_chart({'type': 'scatter',
'subtype': 'straight_with_markers'})
# Configure the chart series. Increase the default marker size for clarity
# and configure the series points to
chart.add_series({
'categories': '=Sheet1!$A$1:$A$6',
'values': '=Sheet1!$B$1:$B$6',
'marker': {'type': 'square',
'size': 12},
'points': [
None,
None,
{'fill': {'color': 'green'},
'border': {'color': 'black'}},
None,
{'fill': {'color': 'red'},
'border': {'color': 'black'}},
],
})
# Turn off the legend for clarity.
chart.set_legend({'none': True})
# Insert the chart into the worksheet.
worksheet.insert_chart('D2', chart)
workbook.close()
Output: