Scatter plot - size from x and y difference

I am trying to create a scatter plot with the size reflecting the difference between the x value and the y value. The size of each data point should be different but I am getting the same size no matter what the x and y values are.


This is my code:

@app.callback(
dash.dependencies.Output(‘bubble_graph’, ‘figure’),
[dash.dependencies.Input(‘xaxis-column’, ‘value’),
dash.dependencies.Input(‘yaxis-column’, ‘value’),
dash.dependencies.Input(‘year–slider’, ‘value’)])
def update_graph(xaxis_column_name, yaxis_column_name,
year_value):
filtered_df = df[df.Year == year_value]
traces = []

for i in filtered_df.group.unique():
	df_by_group = filtered_df[filtered_df['group'] == i]
	traces.append(go.Scatter(
        x=df_by_group[filtered_df['Category'] == xaxis_column_name]['Value'],
        y=df_by_group[filtered_df['Category'] == yaxis_column_name]['Value'],
		text=df_by_group[filtered_df['Category'] == yaxis_column_name]['IndicatorName'],
		mode='markers+text',
		marker=dict(
			sizemode='area',
			sizeref=1,
			size=abs((df_by_group[filtered_df['Category'] == xaxis_column_name]['Value'].iat[-1] - df_by_group[filtered_df['Category'] == yaxis_column_name]['Value'].iat[-1])),
			line=dict(
				width=2
			)
		),
		name = i
	))
traces.append(go.Scatter(
	x = [0,100],
	y = [0,100],
	line = dict(
		color = ('rgba(189,189,189,1)'),
		width = 1,
		dash = 'dot'),
	name='Line of Equality'
))
		
return {
	'data': traces,
	
	'layout': go.Layout(
		xaxis={
			'title': xaxis_column_name,
			'type': 'linear' 
		},
		yaxis={
			'title': yaxis_column_name,
			'type': 'linear' 
		},
		margin={'l': 40, 'b': 40, 't': 10, 'r': 0},
		paper_bgcolor='rgb(243, 243, 243)',
		plot_bgcolor='rgb(243, 243, 243)',
		legend={'x': 0, 'y': 1},
		hovermode='closest',
		autosize=False,
		width=750,
		height=750,

	)

Setting size like this should work. To debug this, I’d try a couple things:

  • Manually print out the data in x, y, and size into a CSV and upload it to the GUI chart editor (https://plot.ly/create). From there, you can manually set x, y, and size and you can look at the JSON view and copy sizemode and sizeref. Here is an example:
  • To set a reasonable sizeref, I recommend using the following formula:
desired_maximum_marker_size = 40 # at most, the marker will be 40px in diameter
sizeref = 2 * np.max(your_list_of_size_values) / (desired_maximum_marker_size**2)
1 Like