How to set the hue range for a numeric variable using a colored bubble plot in seaborn, python?

女生的网名这么多〃 提交于 2021-01-27 19:52:50

问题


I'm trying to use seaborn to create a colored bubbleplot of 3-D points (x,y,z), each coordinate being an integer in range [0,255]. I want the axes to represent x and y, and the hue color and size of the scatter bubbles to represent the z-coordinate.

The code:

import seaborn
seaborn.set()
import pandas
import matplotlib.pyplot

x               = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200]
y               = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200]
z               = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200]

df = pandas.DataFrame(list(zip(x, y, z)), columns =['x', 'y', 'z']) 

ax = seaborn.scatterplot(x="x", y="y",
                 hue="z",
                 data=df)

matplotlib.pyplot.xlim(0,255)
matplotlib.pyplot.ylim(0,255)
matplotlib.pyplot.show()

gets me pretty much what I want:

This however makes the hue range be based on the data in z. I instead want to set the range according to the range of the min and max z values (as 0,255), and then let the color of the actual points map onto that range accordingly (so if a point has z-value 50, then that should be mapped onto the color represented by the value 50 in the range [0,255]).

My summarized question:

  • How to manually set the hue color range of a numerical variable in a scatterplot using seaborn?

I've looked thoroughly online on many tutorials and forums, but have not found an answer. I'm not sure I've used the right terminology. I hope my message got across.


回答1:


Following @JohanC's suggestion of using hue_norm was the solution. I first tried doing so by removing the [hue=] parameter and only using the [hue_norm=] parameter, which didn't produce any colors at all (which makes sense).

Naturally one should use both the [hue=] and the [hue_norm=] parameters.

import seaborn
seaborn.set()
import pandas
import matplotlib.pyplot

x               = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200]
y               = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200]
z               = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 255]

df = pandas.DataFrame(list(zip(x, y, z, my_sizes)), columns =['x', 'y', 'z']) 

ax = seaborn.scatterplot(x="x", y="y",
                 hue="z", 
                 hue_norm=(0,255),        # <------- the solution
                 data=df)

matplotlib.pyplot.xlim(0,255)
matplotlib.pyplot.ylim(0,255)
matplotlib.pyplot.show()


来源:https://stackoverflow.com/questions/60721598/how-to-set-the-hue-range-for-a-numeric-variable-using-a-colored-bubble-plot-in-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!