【问题标题】:Why is my program not generating two graphs at once? I want both graphs to appear within the plot explorer at the same time为什么我的程序没有同时生成两个图表?我希望两个图表同时出现在绘图浏览器中
【发布时间】:2021-12-01 23:55:24
【问题描述】:

通过这个程序,我的目标是使用 panda 导入两个给定文件,并使用该数据创建两个单独的图表。我能够创建图表并将它们保存在不同的文档中,但我的任务要求同时创建它们并在同一个窗口中显示它们。我将如何调整我的代码以使其正常工作?我怀疑我的代码的 file_name 部分存在问题,并且阻止了代码的两个部分正常运行,但我不确定或者它可能是子图部分。

import matplotlib.pyplot as plt
from matplotlib import interactive
import numpy as np


def main(file_name):
    file_name = r"College Enrollments.csv"
    df = pd.read_csv(file_name)
    department = df['Department']
    enrollment_count = df[' Enrollment count']
    
    
    
    plt.figure(figsize= (9,3))
    plt.subplot(131)
    plt.bar(department,enrollment_count)
    plt.title('College Enrollments')
    plt.show
    x_axis = 'Department'
    y_axis = 'Enrollment count'
    plt.yticks(np.arange(0,4001,500))
    plt.xticks(rotation = 90)

    file_name = r"CS Faculty.csv"
    df = pd.read_csv(file_name)
    professor = df['CS Professor']
    yoe = df['Years of Experience']
    #end of graph 1
    
    
    plt.figure(figsize= (9,3))
    plt.subplot(132)
    plt.bar(professor,yoe)
    plt.title('CS Faculty')
    plt.show
    x_axis = 'CS Professor'
    y_axis = 'Years of Experience'
    plt.yticks(np.arange(0,31,5))
    plt.xticks(rotation = 90)

    
   # read the file_name into a pandas dataframe
    
    # plot the dataframe using arguments "title", "legend", "x", "y", "kind" and "color"

    # The only four statements that may use the matplotlib library appear next.
    # Do not modify them.
    plt.xlabel(x_axis)      # Note: x-axis should be determined above
    plt.ylabel(y_axis)      # Note: y-axis should be determined above
    interactive(True)       # This allows multiple figures to be displayed simultaneously
    plt.show()
#end of graph 2
# -------------------------------------------------

main("College Enrollments.csv")
main("CS Faculty.csv")

【问题讨论】:

  • 你应该在最后只调用一次plt.show()。而且plt.figure(...) 也只有一次,在开始时。
  • 如果你覆盖其中的参数并实际循环多个值,那么定义带参数的函数有什么意义?

标签: python pandas matplotlib


【解决方案1】:

我认为您不需要为此编写函数,但您正在寻找类似的东西:

fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle('Horizontally stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y)

最好习惯于查看文档,如果您打算编写任何代码,您将花费大量时间阅读文档。 你可以在这里找到你需要的一切:https://matplotlib.org/devdocs/gallery/subplots_axes_and_figures/subplots_demo.html

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 2021-03-30
    • 2017-03-03
    相关资源
    最近更新 更多