Как создать вертикальную полосу прокрутки на графике с помощью tkinter? - PullRequest
0 голосов
/ 06 мая 2020

Я создал два графика между собой в окне tkinter. На нижнем графике много полосок из-за большого количества данных. По этой причине, чем больше у меня данных, тем меньше масштабируются полосы. Поэтому я хочу дать каждой полосе фиксированную высоту и полосу прокрутки, чтобы можно было прокручивать график вертикально. К сожалению, у меня нет возможности вставить вертикальную полосу прокрутки в график matplotlib с помощью tkinter. Ниже я опубликовал свой код. После кода я создал изображение с проблемой и ожидаемым решением. Я уже пробовал этот метод: Как установить метку галочки yaxis в фиксированное положение, чтобы при прокрутке влево или вправо метка yaxis была видна? , но он работает с моим кодом с помощью вертикальная полоса прокрутки (потому что я python новичок).

# import library
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk 
import tkinter as tk
import numpy as np

# mainwindow initial
root = tk.Tk()
root.title('Plotting')

# data
Beg1 = np.array([3, 2407,   3213,   3516,   4107,   4108,   6685,   12276,  12736,  13306,  15875,  16957,  17150,  18341,  19501,  19506,  23209,  24149,24150,    38365,  41468,  55384,  55691,  71773])
Beg1_number = np.array([5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5])

Beg2 = np.array([1,2,3,100,606,727,783, 805,    1370,   1839,   1849,   2044,   2112,   2219,   2404,   2407,   2443,   2472,   2507,   2536,   2649,   2769,   3042,   3209,   3212,   3250,   3286,   3396,   3434,   3490,   3516,   3517,   3572,   3573,   3583,   3638,   95000])
Beg2_cluster = np.array([21,    3,  47, 1,  1,  1,  1,  1,  2,  2,  27, 2,  1,  2,  9,  3,  14, 4,  1,  10, 1,  1,  2,  2,  20, 18, 1,  3,  3,  5,  34, 1,  13, 11, 1,  30, 30])

Beg3 = np.array([3572,  6685,   6685,   12890,  16955,  17150,  18341,  23209,  24149,  38365,  38365,  38365,  38365,  55384,  55384,  55384,  55384,  71772])
Beg3_number = np.array([5,  5,  10, 5,  5,  5,  5,  5,  5,  5,  10, 15, 20, 5,  10, 15, 20, 5])

Beg4 = np.array([3572,  6685,   6685,   12890,  16955,  17150,  18341,  23209,  24149,  38365,  38365,  38365,  38365,  55384,  55384,  55384,  55384,  71772])
End4 = np.array([3572,  6685,   6685,   12890,  16955,  17150,  18341,  23209,  24149,  38365,  38365,  38365,  38365,  55384,  55384,  55384,  55384,  71772])

Beg5 = np.array([1, 3,  3,  3,  2112,   2443,   2443,   3250,   3250,   3434,   3516,   3572,   3572,   4108,   6685,   12276,  12276,  14168,  15539,  15875,  16017,  16926,  16944,  17150,  17150,  19070,  22116,  24148,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  38280,  38280,  38280,  38280,  38280,  38365,  38365,  38365,  38410,  55291,  55688,  55691,  98555,  98600,  98600,  98600,  98600,  98600,  98608,  98608])
End5 = np.array([3, 2407,   3,  3,  2407,   3213,   3213,   3516,   3516,   3516,   3516,   4107,   4107,   4108,   6685,   13306,  13306,  15875,  15875,  15875,  16957,  16957,  16957,  18341,  18341,  19501,  23209,  24149,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  24150,  38365,  38365,  38365,  38365,  38365,  38365,  38365,  38365,  41468,  55384,  55691,  71773,  98641,  98641,  98641,  98641,  98641,  98641,  98641,  98641])

Beg6 = np.array([6685,  6685,   12276,  18341,  18341,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  61268,  71847,  84286,  95250,  95250,  95250,  95390])
End6 = np.array([6685,  6685,   12276,  18341,  18341,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  55384,  61268,  71847,  84286,  95250,  95250,  95250,  95390])

# frames
frame4 = tk.Frame(root)
frame5 = tk.Frame(root)
frame4.pack()
frame5.pack()

# Plot 1 top
fig, ax = plt.subplots(1, 1, figsize=(30,4))

Plot_Random1 = plt.scatter(Beg1, Beg1_number, 
            marker='x', 
            s=200, 
            color='green', 
            edgecolors='black', 
            zorder=3, 
            label='Random1')

Plot_Random2 = plt.scatter(Beg3, Beg3_number, 
                             marker='s', 
                             s=150, 
                             color='blue', 
                             edgecolors='black', 
                             zorder=3, 
                             label='Random2')

Plot_Random3 = plt.bar(Beg2, Beg2_cluster, 
                             bottom=0, 
                             color='orange', 
                             ec='black', 
                             label='Random3',
                             width=250)

ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_color('none')
ax.tick_params(axis='x', length=20)

_, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
ax.set_xlim(-15, xmax)
ax.set_ylim(ymin, ymax+10) # space for legend
ax.text(xmax, -5, 'Timestep', ha='right', va='top', size=14)
plt.legend(ncol=5, loc='upper left')

# automatic scale plot-width while zoom
def on_xlims_change(axes):
    # current limits of x-axis 
    x_lim = ax.get_xlim()
    x_width = x_lim[1] - x_lim[0]
    # ratio for new width
    new_width = x_width / 100 
    # updating plots with new width
    for b in Plot_Random1:
        b.set_width(new_width)
# set back width
ax.callbacks.connect('xlim_changed', on_xlims_change)

# labeling
fig.suptitle('Plot 1 top')
plt.tight_layout() 

# Plot 2 bottom
fig2, ax2 = plt.subplots(1, 1, figsize=(30,9), facecolor = 'white')         
# Plot 2 bottom
Plot_Random4 = plt.barh(len(Beg6) +len(Beg5)  +np.arange(len(Beg4)),    End4-Beg4+500, 
                   left=Beg4,
                   height=0.9,
                   color='blue',
                   edgecolor='black')

Plot_Random5 = plt.barh(len(Beg6)   +np.arange(len(Beg5)),  End5-Beg5+500, 
                    left=Beg5,
                    height=0.9,
                    color='orange',
                    edgecolor='black')

Plot_Random6 = plt.barh(range(len(Beg6)),   End6-Beg6+500, 
                    left=Beg6,
                    height=0.9,
                    color='green',
                    edgecolor='black')

ax2.spines['bottom'].set_position('zero')
ax2.spines['top'].set_color('none')
ax2.spines['right'].set_color('none')
ax2.spines['left'].set_color('none')

fig2.suptitle('Plot 2 bottom')
plt.ylabel('Random1, Random2, Random3')
plt.tight_layout()

# canvas, toolbar
canvas = FigureCanvasTkAgg(fig, master=frame4)
canvas.draw() # tk drawing area
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
canvas._tkcanvas.pack(side = tk.TOP, fill = tk.BOTH, expand=True)
toolbar = NavigationToolbar2Tk(canvas, frame4)
toolbar.update()

# canvas2, toolbar2
canvas2 = FigureCanvasTkAgg(fig2, master=frame5)
canvas2.draw()
canvas2.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
canvas2._tkcanvas.pack(side = tk.TOP, fill = tk.BOTH, expand=True)
toolbar2 = NavigationToolbar2Tk(canvas2, frame5)
toolbar2.update()

# infinity loop
root.mainloop()

Expected Output

...