英文:
Legend in a specific format
问题
I am plotting a graph with a legend using the following command:
K = [1e3,1e4]
plt.plot(x[:len(y1)], y1, 'o', label=f'Simulation ($K_L$={K[i]:0e})')
which produces the following graph:
But I want the legend to be in a specific format as presented below:
KL = 103
英文:
I am plotting a graph with a legend using the following command:
K = [1e3,1e4]
plt.plot(x[:len(y1)], y1, 'o', label=f'Simulation ($K_L$={K[i]:0e})')
which produces the following graph:
But I want the legend to be in a specific format as presented below:
K<sub>L</sub> = 10<sup>3</sup>
答案1
得分: 1
这部分内容的翻译如下:
import matplotlib.pyplot as plt
def sci_notation(number: float, n_decimals: int = 2) -> str:
sci_notation = f"{number:e}"
decimal_part, exponent = sci_notation.split("e")
decimal_part = float(decimal_part)
exponent = int(exponent)
if decimal_part == 1.0:
return f"$10^{exponent}$"
else:
return f"{decimal_part:.{n_decimals}f}x$10^{exponent}$"
K = [1e3, 1.323423e4]
plt.plot([], [], "o", label=f"Simulation ($K_L$={sci_notation(K[0])})")
plt.plot([], [], "o", label=f"Simulation ($K_L$={sci_notation(K[1])})")
plt.legend()
plt.show()
英文:
What about this? (insipred by this answer).
import matplotlib.pyplot as plt
def sci_notation(number: float, n_decimals: int = 2) -> str:
sci_notation = f"{number:e}"
decimal_part, exponent = sci_notation.split("e")
decimal_part = float(decimal_part)
exponent = int(exponent)
if decimal_part == 1.0:
return f"$10^{exponent}$"
else:
return f"{decimal_part:.{n_decimals}f}x$10^{exponent}$"
K = [1e3, 1.323423e4]
plt.plot([], [], "o", label=f"Simulation ($K_L$={sci_notation(K[0])})")
plt.plot([], [], "o", label=f"Simulation ($K_L$={sci_notation(K[1])})")
plt.legend()
plt.show()
答案2
得分: 1
如果您的图例已经硬编码,您可以这样做:
```python
import numpy as np
import matplotlib.pyplot as plt
K = [1e3, 1e4] # 硬编码的图例
x = np.random.rand(100)
y1 = np.random.rand(100)
plt.plot(
x[:len(y1)],
y1,
'o',
label=f'模拟 ($K_L$=$10^{int(np.log10(K[0]))}$)'
)
plt.legend()
这里将您的 K 的 log10 值手动放在上标(指数)中。
此外,还有一个 scinot
包,可以帮助您更灵活地格式化:
import scinot as sn
a = 1.7e-2
print(sn.format(a))
1.7 × 10⁻²
<details>
<summary>英文:</summary>
If your legend is hardcoded anyway, you can do this:
import numpy as np
import matplotlib.pyplot as plt
K = [1e3,1e4] # hardcoded legend
x = np.random.rand(100)
y1 = np.random.rand(100)
plt.plot(
x[:len(y1)],
y1,
'o',
label=f'Simulation ($K_L$=$10^{int(np.log10(K[0]))}$)'
)
plt.legend()
Here the log10 of your K is put manually in the exponent (superscript).
Also, there is a `scinot` package that might help you formatting more flexible
import scinot as sn
a=1.7e-2
print(scinot.format(a))
1.7 × 10⁻²
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论