import
sys
import
matplotlib.pyplot as plt
from
PyQt5.QtWidgets
import
QApplication, QMainWindow, QVBoxLayout, QWidget, QComboBox
from
matplotlib.backends.backend_qt5agg
import
FigureCanvasQTAgg as FigureCanvas
from
matplotlib.backends.backend_qt5agg
import
NavigationToolbar2QT as NavigationToolbar
class
CustomToolbar(NavigationToolbar):
def
__init__(
self
, canvas, parent
=
None
):
super
(CustomToolbar,
self
).__init__(canvas, parent)
graph_types
=
[
"Line Graph"
,
"Bar Chart"
,
"Scatter Plot"
]
self
.graph_type_combobox
=
QComboBox(
self
)
self
.graph_type_combobox.addItems(graph_types)
self
.graph_type_combobox.currentIndexChanged.connect(
self
._on_graph_type_selected)
self
.addWidget(
self
.graph_type_combobox)
def
_on_graph_type_selected(
self
):
graph_type
=
self
.graph_type_combobox.currentText()
fig
=
self
.canvas.figure
n_plots
=
len
(fig.get_axes())
for
ax
in
fig.get_axes():
ax.remove()
n_new_rows, n_new_cols
=
1
,
1
if
graph_type
=
=
"Line Graph"
:
new_ax
=
fig.add_subplot(n_new_rows, n_new_cols,
1
)
new_ax.plot([
1
,
2
,
3
], [
4
,
2
,
6
], color
=
'blue'
)
new_ax.set_title(
'Line Graph'
)
elif
graph_type
=
=
"Bar Chart"
:
new_ax
=
fig.add_subplot(n_new_rows, n_new_cols,
1
)
bars
=
new_ax.bar([
'A'
,
'B'
,
'C'
], [
3
,
7
,
2
], color
=
[
'red'
,
'green'
,
'blue'
])
new_ax.set_title(
'Bar Chart'
)
elif
graph_type
=
=
"Scatter Plot"
:
new_ax
=
fig.add_subplot(n_new_rows, n_new_cols,
1
)
new_ax.scatter([
1
,
2
,
3
], [
4
,
2
,
6
], color
=
'orange'
)
new_ax.set_title(
'Scatter Plot'
)
fig.canvas.draw()
def
plot_example():
fig, ax
=
plt.subplots(figsize
=
(
10
,
6
))
x_line
=
[
1
,
2
,
3
,
4
]
y_line
=
[
1
,
4
,
2
,
3
]
ax.plot(x_line, y_line, label
=
'Line Graph 1'
, color
=
'red'
)
ax.set_title(
'Line Graph 1'
)
ax.set_xlabel(
'X-axis'
)
ax.set_ylabel(
'Y-axis'
)
ax.legend()
apps
=
QApplication(sys.argv)
main_window
=
QMainWindow()
main_window.setWindowTitle(
"Custom Navigation Toolbar"
)
main_window.setGeometry(
100
,
100
,
800
,
600
)
central_widget
=
QWidget(main_window)
layout
=
QVBoxLayout(central_widget)
canvas
=
FigureCanvas(fig)
custom_toolbar
=
CustomToolbar(canvas, main_window)
layout.addWidget(canvas)
layout.addWidget(custom_toolbar)
main_window.setCentralWidget(central_widget)
main_window.show()
sys.exit(apps.exec_())
plot_example()