python - 在同一个窗口中绘制多种类型的图(折线图、散点图、条形图等)

标签 python matplotlib scatter

我试图在同一窗口中绘制两种类型的图(即线图和散点图)。折线图(第一个图)中绘制的数据是代表气候指数 (Y) 与小数年 (X) 的 float 数值。我想成为“散点图”的第二个图大致相同,但 float 数值表示流量 (Y) 与小数年 (X)。我尝试通过使用双 x 轴和第二个寄生虫 y 轴作为散点图来完成此操作:

    import mpl_toolkits
    from mpl_toolkits.axes_grid1 import host_subplot
    import matplotlib.pyplot as plt

    host = host_subplot(111)
    par = host.twinx()

    host.set_xlim(1880, 2020)
    host.set_ylim(-5, 10)

    host.set_xlabel("Time")
    host.set_ylabel("PDSI Region 01")
    par.set_ylabel("Minimum 10% Annual 7-day Non-exceedance Flow (cfs)")

    x1 = timearray
    y1 = pdsiarray01
    x2 = upAmm_yr
    y2 = upAmm_min

    p1, = host.plot(x1, y1, label="PDSI01")
    p2, = par.scatter(x2, y2, label="Annual Lowflow Upper Amm")

    par.set_ylim(30, 60)

    host.legend()
    host.axis["left"].label.set_color(p1.get_color())
    par.axis["right"].label.set_color(p2.get_color())

    plt.draw()
    plt.show()

我得到了错误代码:

    TypeError: cannot perform reduce with flexible type

当我在以 p2 开头的行中用 plot 替换 scatter 时,这段代码工作正常,但会生成第二个线图。我希望它分散的最终原因是在第二个数据集中要绘制的点要少得多,并且连接它们的线会分散注意力并且“困惑”(当我只需要及时突出显示瞬间)。条形图而不是散点图也可以。任何建议或帮助将不胜感激!

最佳答案

为什么不在这两种情况下都使用plot

import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Generate some random data
time = mdates.drange(datetime.datetime(2010, 1, 1), 
                     datetime.datetime(2011, 1, 1),
                     datetime.timedelta(days=5))
y1 = np.cumsum(np.random.random(time.size) - 0.5)
y2 = np.cumsum(np.random.random(time.size) - 0.5)
y2 = y2 * 20 + 10

# Plot things up...
fig = plt.figure()
host = fig.add_subplot(111)
par = host.twinx()

host.set_ylabel('One Thing')
par.set_ylabel('Another')

line1, = host.plot(time, y1)
line2, = par.plot(time, y2, 'go')
host.legend([line1, line2], ['Item 1', 'Item 2'])

host.xaxis_date()

plt.show()

enter image description here

关于python - 在同一个窗口中绘制多种类型的图(折线图、散点图、条形图等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7352900/

相关文章:

Python 直方图 : Manually normalising counts and re-plotting as histogram

gnuplot - 在 3d 散点图中绘制高度矩阵列表

python - 我如何知道 RSA 算法中我的公钥和私钥是什么?

python - PySide/PyQt 覆盖小部件

python - 带日期的 matplotlib 固定定位器

python - matplotlib继承自datetime类plot

python - 处理字典两点之间的距离

Python Mysql, "commands out of sync; you can' t run this command now"

python - 带有字符串 X 和 Y 坐标的散点图

python - 具有颜色渐变的 Matplotlib 3D 散点图