简体   繁体   中英

How to export the result of a boxplot to a csv file with pandas?

I need to export the result of a boxplot output to a CSV file, but I'm not finding a way to do it.

boxplot = df.boxplot(by='Time', 
                 column='Duration',
                 grid=False,
                 figsize=(16,10))

boxplot.to_csv('BoxplotResult.csv')

In the above example, I get the error: AttributeError: 'AxesSubplot' object has no attribute 'to_csv'.
Which I understand that the result of the boxplot operation is a AxesSubplot and AxesSubplot does not have to_csv method in it.

Is there any way to export the results of a boxplot to a CSV file?

Given you are interested only in the numerical values, a shortcut would describe

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": np.random.randint(5, size=(10)), "B": np.random.randint(8, size=(10))})

df.describe()

Yielding,

            A          B
count   10.000000   10.000000
mean    2.100000    2.000000
std     1.449138    1.763834
min     0.000000    0.000000
25%     1.250000    1.000000
50%     2.000000    1.500000
75%     3.000000    3.500000
max     4.000000    5.000000

This contains all the information needed ( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.describe.html ) and can simply be written to a CSV file as you already pointed out by:

df.describe().to_csv("my_csv.csv")

EDIT

Saving the actual plot can not be done using a CSV file. To do so, use you can simply create a pyplot figure object and plot on its axes like:

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
df.boxplot(grid=False, figsize=(16,10), ax=ax)

fig.savefig("my_figure.png", dpi=72)

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