【问题标题】:Plot two line graphs in same figure with different colours and x and y axis ranges are fixed在同一图中绘制两个不同颜色的折线图,x 和 y 轴范围固定
【发布时间】:2021-08-18 17:58:58
【问题描述】:

我有两个这样的列表

l1= [2, 8, 5, 19, 15, 23]
l2= [3, 5, 8, 11, 14, 50]

现在我想绘制折线图,​​其中 Y 轴的范围为 0 到 50,X 轴的范围为 0 到 50。l1 和 l2 线的颜色不同。如何使用 matplotlib 或 seaborn 做到这一点?

【问题讨论】:

  • X 轴的范围是多少?你的问题不清楚。
  • @Nk03 已编辑。 0到50
  • 而这些点对应x = [0,10,20,30,40,50]?
  • @Nk03 是的,你是对的

标签: matplotlib plot seaborn data-visualization linegraph


【解决方案1】:
  • 将列表加载到pandas 数据帧中。
  • 重构数据框
  • 通过 seaborn 绘制。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

l1= [2, 8, 5, 19, 15, 23]
l2= [3, 5, 8, 11, 14, 50]

df = pd.DataFrame({'l1': l1, 'l2': l2}).stack().reset_index(name='val').assign(level_0 = lambda x: x.level_0 * 10)
sns.set_style('whitegrid')
fg = sns.lineplot(x="level_0", y = "val" , hue="level_1", data=df,  ci=None, palette='Set1')

plt.savefig('test5.png')

输出:

【讨论】:

    【解决方案2】:

    一个简单的解决方案是直接使用matplotlib.pyplot

    import matplotlib.pyplot as plt
        
    l1= [2, 8, 5, 19, 15, 23]
    l2= [3, 5, 8, 11, 14, 50]
    
    plt.ylim((0, 50))  # set Y axis range to 0..50
    plt.xlim((0, 50))  # set X axis range to 0..50
    plt.plot(l1, color='red')  # plot l1
    plt.plot(l2, color='blue') # plot l2
    plt.show()
    

    有关更多样式选项,请参阅matplotlib.pyplot.plot()

    【讨论】:

      猜你喜欢
      • 2015-10-17
      • 2015-09-01
      • 2015-04-04
      • 2020-05-06
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多