i have a dataset containing a array of 2 numbers. the difference of these values should be the bar height. i have the problem that if these numbers are equals the height is zero and so no bar is plotted.
but i need to show these as a very thin line (or dot or something). is subplot with bar(x, height) the wrong way? i tried to add a small value to the difference but my y axis ticks are very dynamic. so adding 0.1 to a scale of 1-100 is okay. i a scale of 0.001-0.05 is way too much.
should i use ax.errorbar() or is there a better way?
edit:\
import matplotlib.pyplot as plt
import pandas as pd
df=pd.DataFrame()
df["desc"] = ("A","B","C","D","E")
df["a"] = (0.1,0.5,1,0.6,0.4)
df["b"] = (0.3,0.6,0.6,0.7,0.4)
fig, ax = plt.subplots()
ax.bar(x=df['desc'],
bottom=df['a'],
height=df['b'] - df['a'])
ax.set_ylim(bottom=0, top=1.2)
new_yticks = list(set(df['a']).union(df['b']))
plt.yticks(new_yticks)
plt.show()
Here you can see that the fifth value (x axis "E") is not plotted. or maybe plotted but no visible due to height zero.
edit2: best approche so far is this:
avg=df["a"].mean()/100
print(avg)
ax.bar(x=df['desc'],
bottom=df['a'],
height=df['b'] - df['a'] avg)
CodePudding user response:
IIUC, you are looking for ``plt.vlines`. Given your imports and data frame, you could use the following code:
x = df["desc"].to_list()
y1 = df["a"].to_list()
y2 = df["b"].to_list()
plt.scatter(x, y1, marker="o", label="a")
plt.scatter(x, y2, marker="x", label="b")
plt.vlines(x, y1, y2, alpha=.8, lw=1, colors="grey")
plt.legend()
plt.show()
which results into this:
You can adjust the style as you like. I just focused on how you can produce the dots and thin vertical lines.
CodePudding user response:
You cancreate a variable difference.
Then check when difference is 0 and assign a minimal value.
If the value is too small nothing will be plotted so you will have to tune it a bit.
import matplotlib.pyplot as plt
import pandas as pd
df=pd.DataFrame()
df["desc"] = ("A","B","C","D","E")
df["a"] = (0.1,0.5,1,0.6,0.4)
df["b"] = (0.3,0.6,0.6,0.7,0.4)
difference = df["a"] - df["b"]
difference[difference == 0] = 0.01
fig, ax = plt.subplots()
ax.bar(x=df['desc'],
bottom=df['a'],
height=difference)
ax.set_ylim(bottom=0, top=1.2)
new_yticks = list(set(df['a']).union(df['b']))
plt.yticks(new_yticks)
plt.show()