Matplotlib如何实现标注框内多行文本的列对齐?
Hey Andrea, I’ve run into this exact issue before—Matplotlib doesn’t play nice with tab characters (\t) for text box alignment, which is why your initial attempt didn’t work. The good news is there’s a simple fix using fixed-width string formatting to make those columns line up perfectly.
Solution: Use Fixed-Width String Fields
Instead of concatenating strings with \t, we can format each line to give the names a consistent width. This ensures the colons and height values all align neatly, no matter how long or short the names are.
Here’s how to update your text_to_show variable:
# Format each line with left-aligned names (fixed 20-character width) text_to_show = ( f"{'Andrea':<20} : 1.95 m\n" f"{'Paja':<20} : 1.65 m\n" f"{'Franco':<20} : 1.80 m\n" f"{'Benna':<20} : 1.55 m\n" f"{'Iandool':<20} : 1.80 m\n" f"{'Giammai':<20} : 1.82 m\n" f"{'Celestina':<20} : 0.50 m\n" f"{'GioelipeAnderson':<20} : 1.00 m" )
How It Works
- The
:<20syntax in the f-string tells Python to left-align the name and pad it with spaces to fill exactly 20 characters. - You can adjust the
20to a smaller or larger number depending on how much space you want for the names (just make sure it’s longer than your longest name, which isGioelipeAndersonhere).
Alternative: Using str.ljust()
If you prefer a more explicit approach, you can use the ljust() string method to pad each name to a fixed width:
# Create a list of formatted lines height_data = [ ("Andrea", "1.95 m"), ("Paja", "1.65 m"), ("Franco", "1.80 m"), ("Benna", "1.55 m"), ("Iandool", "1.80 m"), ("Giammai", "1.82 m"), ("Celestina", "0.50 m"), ("GioelipeAnderson", "1.00 m") ] # Format each line with left-aligned names text_lines = [f"{name.ljust(20)} : {height}" for name, height in height_data] text_to_show = "\n".join(text_lines)
Updated Full Code Snippet
Replace your original text_to_show definition with either of the above options, and your green text box will have perfectly aligned columns. The rest of your plotting code can stay exactly the same.
When you run the updated code, the names will all occupy the same width, making the height values line up neatly in a single column—no more messy, uneven text!
内容的提问来源于stack exchange,提问作者Andrea Ianni

