我想用腳本中提到的資料繪制一個漂亮的柱狀圖。此外,X軸應該是對數,而且條形圖之間必須有空隙。
我嘗試了以下的腳本:
我嘗試了以下的腳本。
importmatplotlib.pyplot as plt
import numpy as np
import pandas as pd
fig = plt.figure()
x = [0.000001,0.00001,0.0001,0。 001,0.01,0.1,1.0]
height = [5.3,1.8,8.24, 5. 8,2.8,3.3,4.2]
寬度= 0.000001]
plt.bar(x, height, width, color='b'/span> )
plt.xscale("log")
plt.savefig('SimpleBar.png')
plt.show()
然而,X軸的值并沒有像預期的那樣被繪制出來。
uj5u.com熱心網友回復:
對于一個對數比例的X軸,你不能為條形圖設定恒定的寬度。例如,第一個條形圖將在0和0.000002之間,(0在對數刻度上是負無窮大)
你可以用x-position來表示條形圖的左邊緣,而用下一個x-position來表示右邊緣:
importmatplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x = [0.000001, 0.00001, 0.0001, 0。 001, 0.01, 0.1, 1.0]
高度 = [5.3, 1.8, 8.24, 5。 8, 2.8, 3.3, 4.2]
plt.xscale("log")
widths = np.diff(x [x[-1] * 10] )
plt.bar(x, height, widths, align='edge', facecolor='dodgerblue', edgecolor='white', lw= 2)
plt.show()
如果你想讓條形圖圍繞原始x值 "居中",你需要計算每個條形圖在對數空間中的開始和結束位置。最簡單的方法是設定一個較厚的白色邊框,以獲得更多的條形圖之間的間距。
importmatplotlib.pyplot as plt
import numpy as np
x = [0.000001, 0.00001, 0.0001, 0。 001, 0.01, 0.1, 1.0]
高度 = [5.3, 1.8, 8.24, 5。 8, 2.8, 3.3, 4.2]
plt.xscale("log")
padded_x = [x[0] / 10] x [x[-1] * 10]
centers = [np. sqrt(x0 * x1) for x0, x1 in zip(padded_x[: -1], padded_x[1:])]
widths = np.diff(center)
plt. bar(center[: -1], height, widths, align='edge', facecolor='dodgerblue', edgecolor='white', lw=4)
plt.margins(x=0.01)
plt.show()
如果你為每個條形圖計算新的左右位置,你也可以有一個可配置的寬度:
importmatplotlib.pyplot as plt
import numpy as np
x = [0.000001, 0.00001, 0.0001, 0。 001, 0.01, 0.1, 1.0]
高度 = [5.3, 1.8, 8.24, 5。 8, 2.8, 3.3, 4.2]
plt.xscale("log")
padded_x = [x[0] / 10] x [x[-1] * 10]
width = 0.3 # 1為全寬,接近于0為較細的條形圖。
lefts = [x1 ** (1 - width / 2) * x0 ** (width / 2) for x0, x1 in zip(padded_x[: -2], padded_x[1:-1])]
權利 = [x0 ** (1 - width / 2) * x1 ** (width / 2) for x0, x1 in zip(padded_x[1: -1], padded_x[2:])]
widths = [r - l for l, r in zip(lefts, rights)]
plt.bar(lefts, height, widths, align='edge', facecolor='daodgerblue', lw=0)
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/309465.html
標籤:




