我在饼图中添加了旋转标签,并希望默认情况下标签将位于饼图的每个切片中。但这不是
如何将标签居中?
这是我的后端代码:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget
from frontend import Ui_MainWindow
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
class Ui_MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(Ui_MainWindow, self).__init__(parent)
self.setupUi(self)
self.graph = MyCanvas()
self.gridLayout.addWidget(self.graph, 0, 0, 1, 1)
self.graph.figure.clf()
self.axes = self.graph.figure.add_subplot(111)
self.y = [1,2,3, 4,8,16,32]
self.label = ['1.52%', '3.03%', '4.55%', '6.06%', '12.12%', '24.24%', '48.48%']
self.axes.pie(self.y, labels=self.label, labeldistance=0.6, rotatelabels =True)
class MyCanvas(FigureCanvas):
def __init__(self, *args, **kwargs):
self.figure = plt.figure()
FigureCanvas.__init__(self, self.figure)
self.figure.patch.set_facecolor("None")
self.figure.subplots_adjust(left=0.08, bottom=0.10, right=0.99, top=0.97)
if __name__ == '__main__':
app = QApplication(sys.argv)
prog = Ui_MainWindow()
prog.show()
sys.exit(app.exec_())
答案 0 :(得分:2)
查看documentation,您可以使用textprops
关键字将专用选项传递给饼图中的文本对象。 textprops
接受dict
,它显然接受matplotlib.text.Text接受的所有选项。向其提供选项rotation_mode='anchor'
,va='center'
和ha='left'
可获得很好的效果:
import matplotlib.pyplot as plt
figure = plt.figure()
figure.patch.set_facecolor("None")
figure.subplots_adjust(left=0.08, bottom=0.10, right=0.99, top=0.97)
figure.clf()
axes = figure.add_subplot(111)
axes.set_aspect(1)
y = [1,2,3, 4,8,16,32]
label = ['1.52%', '3.03%', '4.55%', '6.06%', '12.12%', '24.24%', '48.48%']
axes.pie(
y, labels=label, labeldistance=0.6, rotatelabels =True,
textprops = dict(rotation_mode = 'anchor', va='center', ha='left'),
)
plt.show()
代码的结果如下:
请注意,我添加了ax.set_aspect(1)
以使饼图成为圆形。如果您不希望这样做,则请忽略该行。