英文:
How to insert string into plotting function in python
问题
for plot_type in plot_type_list:
if plot_type == 'histplot':
ax = sns.histplot(data=data, y=value, x=category)
elif plot_type == 'boxplot':
ax = sns.boxplot(data=data, y=value, x=category)
elif plot_type == 'violinplot':
ax = sns.violinplot(data=data, y=value, x=category)
ax.figure.set_size_inches(7, 10)
plt.title('Title')
plt.show()
在你的for循环中,你可以根据plot_type的值来选择不同的绘图类型,然后调用相应的seaborn绘图函数,如histplot、boxplot和violinplot。这样可以根据plot_type的值创建不同类型的图形。
英文:
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?
答案1
得分: 1
你可以使用Python内置的eval()
函数。
你需要用以下代码替换你的一行代码:
ax = sns.plot_type(data=data, y=value, x=category)
使用
ax = eval("sns." + plot_type)(data=data, y=value, x=category)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论