Title: [Bug]: Text rotation leads to characters being misplaced within their bounding boxes. Attempted solution provided. · Issue #23021 · matplotlib/matplotlib · GitHub
Open Graph Title: [Bug]: Text rotation leads to characters being misplaced within their bounding boxes. Attempted solution provided. · Issue #23021 · matplotlib/matplotlib
X Title: [Bug]: Text rotation leads to characters being misplaced within their bounding boxes. Attempted solution provided. · Issue #23021 · matplotlib/matplotlib
Description: Bug summary plt.text(...) is not rotating text correctly. This becomes clear when looking at their bounding boxes, where you can see that a character's position within the bounding box differs depending on the rotation (and sometimes, th...
Open Graph Description: Bug summary plt.text(...) is not rotating text correctly. This becomes clear when looking at their bounding boxes, where you can see that a character's position within the bounding box differs depe...
X Description: Bug summary plt.text(...) is not rotating text correctly. This becomes clear when looking at their bounding boxes, where you can see that a character's position within the bounding box differs ...
Opengraph URL: https://github.com/matplotlib/matplotlib/issues/23021
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"[Bug]: Text rotation leads to characters being misplaced within their bounding boxes. Attempted solution provided.","articleBody":"### Bug summary\r\n\r\nplt.text(...) is not rotating text correctly. This becomes clear when looking at their bounding boxes, where you can see that a character's position within the bounding box differs depending on the rotation (and sometimes, the text will even exit the box).\r\n\r\n### Code for reproduction\r\n\r\n```python\r\nimport matplotlib.pyplot as plt\r\n\r\ndef plot_rotation_period(y, rotation, r):\r\n c0 = plt.gca().annotate('.', xy=(0.5, y), xytext=(0.5, y), rotation=rotation, fontsize=80,\r\n rotation_mode='anchor', fontfamily='monospace', va='bottom', ha='center',\r\n transform_rotates_text = False)\r\n\r\n bb0 = c0.get_window_extent(renderer=r).transformed(plt.gca().transData.inverted())\r\n rect0 = plt.Rectangle((bb0.x0, bb0.y0), bb0.width, bb0.height,\r\n facecolor=\"C1\", alpha=0.3, zorder=2)\r\n plt.gca().add_patch(rect0)\r\n\r\nif __name__ == '__main__':\r\n fig = plt.gcf()\r\n r = fig.canvas.get_renderer()\r\n fig.set_size_inches(15, 15)\r\n\r\n plt.xlim(0, 1)\r\n plt.ylim(0, 1)\r\n\r\n plot_rotation_period(0.8, 0, r)\r\n print('1')\r\n plot_rotation_period(0.6, 90, r)\r\n print('2')\r\n plot_rotation_period(0.4, 180, r)\r\n print('3')\r\n plot_rotation_period(0.2, 270, r)\r\n\r\n plt.plot([0.5, 0.5], [0, 1], linestyle='--')\r\n plt.show()\r\n\r\n# plt.savefig('example_C.png') # this issue becomes a bit clearer if you do plt.savefig()\r\n```\r\n\r\n\r\n### Actual outcome\r\n\r\nThese examples were created from the code above, which rotates the text 0/90/180/270 degrees and plots its bonding box. When the character is a \".\", it looks like this: https://imgur.com/dBgTRBA\r\n\r\nThe \".\" makes the issue obvious, although this issue appears for all characters, e.g., \"C\": https://imgur.com/a/u3UamAb\r\n\r\nChanging the horizontal/vertical alignment does not fix this. I tried every possible combination, and although it moves the text around, it never does so never in the correct way.\r\n\r\n### Expected outcome\r\n\r\nCorrect outcome for \"C\": https://imgur.com/2XT7wdA\r\nCorrect outcome for \".\": https://imgur.com/Zx22cV1\r\n\r\nHere, we can see that the character is in the same position relative to its bounding box for each possible rotation.\r\n\r\n### Additional information\r\n\r\nI took a stab at trying to fix this. It seems like the issue is related to the [Descent](https://freetype.org/freetype2/docs/glyphs/glyphs-3.html) and/or [Offset/Bearing](https://freetype.org/freetype2/docs/tutorial/step2.html) of the font.\r\n\r\nI took a look at backend_agg.py, where the text is being drawn. My solution may is quite crude and violates [Chesterton's fence](https://en.wiktionary.org/wiki/Chesterton%27s_fence#:~:text=Chesterton's%20fence%20(uncountable),state%20of%20affairs%20is%20understood.). However, I found that if I comment out some lines in backend_agg.RendererAgg.draw_text(...), this fixes the issue ([highlighted here](https://imgur.com/a/u3UamAb)):\r\n\r\n```Python\r\n def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):\r\n # docstring inherited\r\n\r\n if ismath:\r\n return self.draw_mathtext(gc, x, y, s, prop, angle)\r\n\r\n flags = get_hinting_flag()\r\n font = self._get_agg_font(prop)\r\n if font is None:\r\n return None\r\n # We pass '0' for angle here, since it will be rotated (in raster\r\n # space) in the following call to draw_text_image).\r\n\r\n font.set_text(s, 0, flags=flags)\r\n font.draw_glyphs_to_bitmap(\r\n antialiased=mpl.rcParams['text.antialiased'])\r\n\r\n d = font.get_descent() / 64.0\r\n #The descent needs to be adjusted for the angle. [original comment from the package]\r\n # xo, yo = font.get_bitmap_offset() [I deleted these next lines, commented out here]\r\n # xo /= 64.0 \r\n # yo /= 64.0 \r\n # xd = d * sin(radians(angle)) \r\n # yd = d * cos(radians(angle))\r\n # x = round(x + xo + xd)\r\n # y = round(y + yo + yd)\r\n self._renderer.draw_text_image(font, x, y + 1, angle, gc)\r\n```\r\n\r\nBy commenting out those lines, I was able to generate those expected outcome pictures above. I tried this for serif fonts and different vertical/horizontal alignments, and it seems to work as expected. Should I do a PR (or would further tests be needed, if so which)?\r\n\r\nI'm having trouble understanding why this code would be here in the first place. Maybe there was some code changed upstream/downstream which already addresses the offset/descent issue, and so the code I pointed out is doing it again, leading to problems?\r\n\r\nI think someone before tried to come up with a solution for a related problem ([see issue](https://github.com/matplotlib/matplotlib/issues/13044)), although their fix was not accepted.\r\n\r\n### Operating system\r\n\r\nWindows 10\r\n\r\n### Matplotlib Version\r\n\r\n3.4.3\r\n\r\n### Matplotlib Backend\r\n\r\nQt5Agg\r\n\r\n### Python version\r\n\r\n3.8.12\r\n\r\n### Jupyter version\r\n\r\n_No response_\r\n\r\n### Installation\r\n\r\nconda","author":{"url":"https://github.com/paulcbogdan","@type":"Person","name":"paulcbogdan"},"datePublished":"2022-05-09T17:51:20.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":1},"url":"https://github.com/23021/matplotlib/issues/23021"}
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:640e63b2-5193-76e9-c9cf-c3db7618a5fd |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | A30C:69D3C:279B999:34F07DF:6A52180C |
| html-safe-nonce | 60e1904b19bd23d6f598fb1fb7480ed1a5bab833a0765d5fa7129457b0f80d7e |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBMzBDOjY5RDNDOjI3OUI5OTk6MzRGMDdERjo2QTUyMTgwQyIsInZpc2l0b3JfaWQiOiI4NzQyNTE1MjEzOTM5NjQ0NDI4IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 9cb282310f0349a32691efec1d6182581f20f49bcb86967ea08e54a0556d2238 |
| hovercard-subject-tag | issue:1230054485 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/matplotlib/matplotlib/23021/issue_layout |
| twitter:image | https://opengraph.githubassets.com/9a56e57a9d68a739da1a780a32436d381caafca5b022f1c244dbdfa27e06cd40/matplotlib/matplotlib/issues/23021 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/9a56e57a9d68a739da1a780a32436d381caafca5b022f1c244dbdfa27e06cd40/matplotlib/matplotlib/issues/23021 |
| og:image:alt | Bug summary plt.text(...) is not rotating text correctly. This becomes clear when looking at their bounding boxes, where you can see that a character's position within the bounding box differs depe... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | paulcbogdan |
| hostname | github.com |
| expected-hostname | github.com |
| None | b9a586c06a05a7a86fc7e3f4dbd03e42f6869085879aa184aa6369456dbd50fb |
| turbo-cache-control | no-preview |
| go-import | github.com/matplotlib/matplotlib git https://github.com/matplotlib/matplotlib.git |
| octolytics-dimension-user_id | 215947 |
| octolytics-dimension-user_login | matplotlib |
| octolytics-dimension-repository_id | 1385122 |
| octolytics-dimension-repository_nwo | matplotlib/matplotlib |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 1385122 |
| octolytics-dimension-repository_network_root_nwo | matplotlib/matplotlib |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 7aed05249554b889eb33d002851a973eebcc7e91 |
| ui-target | canary-1 |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width