简体   繁体   中英

How to use pandas df.plot.scatter to make a figure with subplots

Hello how can i make a figure with scatter subplots using pandas? Its working with plot, but not with scatter.

Here an Example

import numpy as np
import pandas as pd
matrix = np.random.rand(200,5)

df = pd.DataFrame(matrix,columns=['index','A','B','C','D'])

#single plot, working with 
df.plot(
        kind='scatter',
        x='index',
        y='A',
        s= 0.5
        )

# not workig
df.plot(
        subplots=True,
        kind='scatter',
        x='index',
        y=['A','B','C'],
        s= 0.5
        )

Error

raise ValueError(self._kind + " requires an x and y column")
ValueError: scatter requires an x and y column

Edit: Solution to make a figure with subplots with using df.plot (Thanks to @Fourier)

import numpy as np
import pandas as pd

matrix = np.random.rand(200,5)#random data
df = pd.DataFrame(matrix,columns=['index','A','B','C','D']) #make df

#get a list for subplots
labels = list(df.columns)
labels.remove('index')

df.plot(
  layout=(-1, 5), 
  kind="line", 
  x='index', 
  y=labels, 
  subplots = True, 
  sharex = True, 
  ls="none", 
  marker="o")

Would this work for you:

import pandas as pd
import numpy as np

df = pd.DataFrame({"index":np.arange(5),"A":np.random.rand(5),"B":np.random.rand(5),"C":np.random.rand(5)})

df.plot(kind="line", x="index", y=["A","B","C"], subplots=True, sharex=True, ls="none", marker="o")

Output

在此处输入图片说明

Note: This uses a line plot with invisible lines. For a scatter, I would go and loop over it.

for column in df.columns[:-1]: #[:-1] ignores the index column for my random sample
    df.plot(kind="scatter", x="index", y=column)

EDIT

In order to add custom ylabels you can do the following:

axes = df.plot(kind='line', x="index", y=["A","B","C"], subplots=True, sharex=True, ls="none", marker="o", legend=False)

ylabels = ["foo","bar","baz"]

for ax, label in zip(axes, ylabels):    
    ax.set_ylabel(label)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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