【问题标题】:How do I change a bar graph to a line graph in python?如何在python中将条形图更改为折线图?
【发布时间】:2018-09-09 04:45:40
【问题描述】:

我对 python 很陌生,但我制作了一个程序,它可以在折线图上生成我想要的数据。我知道如何使用条形图,但是我没有找到任何方法(我可以理解或可以使用而不会抛出错误)来制作折线图。

这是我尝试绘制一些数据的示例:

import matplotlib.pyplot as plt
x = []
y = []
width = 0.5
for i in range(100):
    x.append(i)
    y.append(i)
_ = plt.xlabel('Number of moves')
_ = plt.ylabel('Frequnecy')
_ = plt.bar(x, y, color='r', width=width)
plt.show()   

我只想知道如何将 for 循环中的数据转换为折线图。试着想想最简单的方法,因为我不是很聪明。将不胜感激附加到解决方案的解释。

干杯,埃文。

编辑:感谢回答者,我解决了这个问题。我还想知道如何为图表添加标题,还想知道如何增加 x 轴线的长度(我的图表的数据有点被压扁)。

【问题讨论】:

标签: python matplotlib plot graph linegraph


【解决方案1】:

使用plt.plot 而不是plt.bar 得到折线图

_ = plt.plot(x, y, color='r')
plt.show()

【讨论】:

  • 非常感谢!几个问题:为什么不让我添加宽度参数?是否有任何参数可以分散数据(即增加 x 轴的长度)?
【解决方案2】:

使用plt.plot 使用折线图,使用plt.title 为图表添加标题。

plt.title("this is a title")
plt.show()

【讨论】:

    【解决方案3】:

    我建议您在下面的链接中阅读本教程

    https://matplotlib.org/gallery/lines_bars_and_markers/simple_plot.html

    对于线宽调整,您只需将 linewidth 参数作为

    传递给绘图函数

    plt.plot(x, y, linewidth=2.0)

    如果我没记错的话,您也想知道调整绘图的轴限制。这可以通过plt.xlim(5, 0) 完成。更多内容请查看

    https://matplotlib.org/api/_as_gen/matplotlib.pyplot.xlim.html

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多