简体   繁体   English

在python plt.plot中使用一系列作为标记

[英]using a series as markersize in python plt.plot

Is it possible to use a column in a dataframe to scale the marker size in matplotlib? 是否可以使用数据框中的列来缩放matplotlib中的标记大小? I keep getting an error about using a series when I do the following. 当我执行以下操作时,我一直收到有关使用系列的错误消息。

import pandas as pd
import matplotlib.pyplot as plt

my_dict = {'Vx': [16,25,85,45], 'r': [1315,5135,8444,1542], 'ms': [10,50,100, 25]}
df= pd.DataFrame(my_dict)
fig, ax = plt.subplots(1, 1, figsize=(20, 10))
ax.plot(df.Vx, df.r, '.', markersize= df.ms)

when I run 我跑的时候

ValueError: setting an array element with a sequence.

I'm guessing it does not like the fact that Im feeding a series to the marker, but there must be a way to make it work... 我猜它不喜欢我给标记喂食系列的事实,但必须有办法让它起作用......

Better to use the built-in scatter plot function in pandas where you can pass a whole series object as the size param to vary the bubble size: 最好在pandas中使用内置的散点图函数,您可以将整个系列对象作为大小参数传递以改变气泡大小:

df.plot.scatter(x=['Vx'], y=['r'], s=df['ms'], c='g')  # df['ms']*5 bubbles more prominent

在此输入图像描述


Or, if you want to go via the matplotlib route, you need to pass a scalar value present in the series object each time to the markersize arg. 或者,如果要通过matplotlib路径,则需要每次将series对象中存在的标量值传递给markersize arg。

fig, ax = plt.subplots()
[ax.plot(row['Vx'], row['r'], '.', markersize=row['ms']) for idx, row in df.iterrows()]
plt.show()

在此输入图像描述

Use plt.scatter instead of plt.plot . 使用plt.scatter而不是plt.plot Scatter lets you specify the size s as well as the color c of the points using a tuple or list. Scatter允许您使用元组或列表指定大小s以及点的颜色c

import pandas as pd
import matplotlib.pyplot as plt

my_dict = {'Vx': [16,25,85,45], 'r': [1315,5135,8444,1542], 'ms': [10,50,100, 25]}
df= pd.DataFrame(my_dict)
fig, ax = plt.subplots(1, 1, figsize=(20, 10))
ax.scatter(df.Vx, df.r, s= df.ms)
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM