0

I have the following code that creates a histogram from my data using seaborn in python:

ax=sns.histplot(data=data, y=value, x=category)
            ax.figure.set_size_inches(7,len(10))
            plt.title('Title'.format(field))
            plt.show()

Now I want to work on creating a for loop that creates a different type of plot for my data from a list of data types. Specifically, for my data, I want to create a histogram, a boxplot, and violin plot from my data using seaborn.

And so, I have this list of seaborn plot types:

plot_type_list = ['histplot', 'boxplot', 'violinplot]

And so I want to loop through this list of plot types and try each plot type for my data. I try the following:

for plot_type in plot_type_list:
     ax=sns.plot_type(data=data, y=value, x=category)
          ax.figure.set_size_inches(7,len(10))
          plt.title('Title'.format(field))
          plt.show()

My reasoning here was that the "plot_type" in sns.plot_type() would be substituted by each string in my plot_type_list, thus creating each type of plot from my data. However, this code attempt returns the following error:

AttributeError: module 'seaborn' has no attribute 'plot_type_list'

I see that python is not inserting my plot_type string into the seaborn plotting function as I intended, rather just preserving "plot_type" as "plot_type", rather than "histplot", "boxplot", and "violinplot". How can I fix my code so that the seaborn plotting function has each plot type inserted, such that for through my for loop, I can create a histplot, boxplot, and violinplot?

6
  • where is your data? Please attach your data along with a post to get a better solution by community. Commented Feb 8, 2023 at 6:20
  • getattr(sns, plot_type)(data=data, y=value, x=category) Commented Feb 8, 2023 at 6:21
  • 1
    Try with replace ax=sns.plot_type(data=data, y=value, x=category) line with ax = eval("sns." + plot_type)(data=data, y=value, x=category) Commented Feb 8, 2023 at 6:22
  • If it useful then you can mark as answer and upvote for other users who have similar problem in future. Cheers! Commented Feb 8, 2023 at 6:34
  • Maybe for kind in ['hist','violin','box']: with sns.catplot(data=data, y=value, x=category, kind=kind, height=7, aspect=1.5) works for you? See seaborn catplot. Commented Feb 8, 2023 at 7:25

1 Answer 1

1

You can use Python's built-in eval() function.

You need to replace your line of code :

ax=sns.plot_type(data=data, y=value, x=category)

with

ax = eval("sns." + plot_type)(data=data, y=value, x=category)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.