Created
December 26, 2020 20:21
-
-
Save peace899/502f5e665ebe6ee438279d05dcb70573 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PyQt5.QtWidgets import QApplication, QMainWindow, QToolTip | |
import sys | |
from PyQt5.QtChart import QChart, QChartView, QBarSet, QPercentBarSeries, QBarCategoryAxis | |
from PyQt5.QtGui import QPainter, QPixmap, QTransform | |
from PyQt5.QtCore import Qt, QPointF, QRect | |
from functools import partial | |
class Window(QMainWindow): | |
def __init__(self): | |
super().__init__() | |
self.setWindowTitle("PyQt BarChart") | |
self.setGeometry(100,100, 480,300) | |
self.show() | |
self.create_bar() | |
def create_bar(self): | |
series = QPercentBarSeries() | |
set_items = {"Parwiz":[1 , 2 , 3 , 4 , 5 , 6], | |
"Bob":[ 5 , 0 , 0 , 4 , 0 , 7], | |
"Tom":[3 , 5 , 8 , 13 , 8 , 5], | |
"Logan":[ 5 , 6 , 7 , 3 , 4 , 5], | |
"Karim":[9, 7, 5, 3, 1, 6]} | |
for name, values in set_items.items(): | |
_set = QBarSet(name) | |
_set.append(values) | |
_set.hovered.connect(partial(self.show_tooltip, _set.label(), values)) | |
_set.doubleClicked.connect(self.resetZoom) | |
series.append(_set) | |
self.chart = QChart() | |
self.chart.addSeries(series) | |
self.chart.setTitle("Percent Example") | |
self.chart.setAnimationOptions(QChart.SeriesAnimations) | |
self.categories = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] | |
axis = QBarCategoryAxis() | |
axis.append(self.categories) | |
self.chart.createDefaultAxes() | |
self.chart.setAxisX(axis, series) | |
self.chart.legend().setVisible(True) | |
self.chart.legend().setAlignment(Qt.AlignBottom) | |
chartView = QChartView(self.chart) | |
chartView.setRenderHint(QPainter.Antialiasing) | |
chartView.setGeometry(100,100, 800,480) | |
chartView.setInteractive(True) | |
chartView.setRubberBand(chartView.RectangleRubberBand) | |
self.setCentralWidget(chartView) | |
def show_tooltip(self, label, values): | |
hoverPoint = QPointF(self.chart.cursor().pos().x() - self.x(), | |
self.chart.cursor().pos().y() - self.y()) | |
bar_coords = self.chart.mapToValue(hoverPoint) | |
index_ = int(round(bar_coords.x(),0)) | |
try: | |
category = self.categories[index_] | |
text = f'Label: {label}\nCategory: {category}\nValue: {values[index_]}' | |
QToolTip.showText(self.chart.cursor().pos(), text, self) | |
except IndexError: #Out of chart range | |
pass | |
App = QApplication(sys.argv) | |
window = Window() | |
sys.exit(App.exec_()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment