kiwi_kimchi
kiwi_kimchi

Reputation: 423

Removing the white border in the bar graph in python

so I found this code here in stackover flow: Plot on primary and secondary x and y axis with a reversed y axis

#1 Import Library

import matplotlib.pyplot as plt
%matplotlib
import numpy as np
import pandas as pd

#2 IMPORT DATA  
sfData=pd.read_excel('data/streamflow validation.xlsx',sheet_name='Sheet1')

#3 Define Data
x = sfData['Year']
y1 = sfData['Observed']
y2 = sfData['Simulated']
y3 = sfData['Areal Rainfall']

# Or we can use loc for defining the data
x = list(sfData.iloc[:, 0])
y1 = list(sfData.iloc[:, 1])
y2 = list(sfData.iloc[:, 2])
y3 = list(sfData.iloc[:, 3])

#4 Plot Graph
fig, ax1 = plt.subplots(figsize=(12,10))
# increase space below subplot
fig.subplots_adjust(bottom=0.3)
# Twin Axes
# Secondary axes
ax2 = ax1.twinx()
ax2.bar(x, y3, width=15, bottom=0, align='center', color = 'b', data=sfData)
ax2.set_ylabel(('Areal Rainfall(mm)'),
            fontdict={'fontsize': 12})
# invert y axis
ax2.invert_yaxis()
# Primary axes
ax1.plot(x, y1, color = 'r', linestyle='dashed', linewidth=3, markersize=12)
ax1.plot(x, y2, color = 'k', linestyle='dashed', linewidth=3, markersize=12)

#5 Define Labels
ax1.set_xlabel(('Years'),
           fontdict={'fontsize': 14})
ax1.set_ylabel(('Flow (m3/s)'),
               fontdict={'fontsize': 14})

#7 Set limit 
ax1.set_ylim(0, 45)
ax2.set_ylim(800, 0)
ax1.set_xticklabels(('Jan 2003', 'Jan 2004', 'Jan 2005', 'Jan 2006', 'Jan 2007', 'Jan 2008', 'Jan 2009' ),
                    fontdict={'fontsize': 13})
for tick in ax1.get_xticklabels():
    tick.set_rotation(90)

#8 set title
ax1.set_title('Stream Flow Validation 1991', color = 'g')

#7 Display legend
legend = fig.legend()
ax1.legend(['Observed', 'Simulated'], loc='upper left', ncol=2, bbox_to_anchor=(-.01, 1.09))
ax2.legend(['Areal Rainfall'], loc='upper right', ncol=1, bbox_to_anchor=(1.01, 1.09))

#8 Saving the graph
fig.savefig('output/figure1.png')
fig.savefig('output/figure1.jpg')

However, my output figure becomes like this: enter image description here

Now I wonder how can I delete those white parts so it can just show purely blue bar graphs?

In one of my datasets, it worked perfectly fine, just like below: enter image description here

but i would love to delete those white border in the bar graph so it won't end up like the first picture in any of the future datasets.

Upvotes: 1

Views: 660

Answers (2)

Lorenzothetall
Lorenzothetall

Reputation: 1

To summarize the answers given in matplotlib bar graph black - how do I remove bar borders

There are two main ways to remove the white edgecolor: 1. Changing linewidth 2. Changing edgecolor

  1. Changing linewidth to zero => good results, added benefit of keeping hatch petterns

Mentioned in Docs of bar plot as

linewidth: float or array-like, optional Width of the bar edge(s). If 0, don't draw edges.

bar(. . . , linewidth=0)
  1. A: Changing edgecolor to the bar color => gives fuzzy results
bar(. . . , edgecolor="b")
  1. B: Changing edgecolor to "none" => also good results
bar(. . . , edgecolor="none")

Origin: The default edgecolor is black but for example setting seaborn style to whitegrid once will result in the described Problem.

Example to test:

import matplotlib.pyplot as plt
import seaborn as sns
#sns.set_style("whitegrid") # once called edgecolor will be white
fig, axs = plt.subplots(1, 4, figsize=(8, 3))

# Bars with hatching default edgecolor
axs[0].bar([1, 1.5, 2], [3, 5, 2], color='b', hatch='//')
axs[0].set_title('default')

# Bars with hatching and edgecolor="none" (hatching disappears)
axs[1].bar([1, 1.5, 2], [3, 5, 2], hatch='//', edgecolor="none", color='b')
axs[1].set_title('edgecolor="none"')

# Bars with hatching and edgecolor="b" (hatching disappears)
axs[2].bar([1, 1.5, 2], [3, 5, 2], hatch='//', edgecolor="b", color='b')
axs[2].set_title('edgecolor="b"')

# Bars with hatching and linewidth=0 (hatching remains)
axs[3].bar([1, 1.5, 2], [3, 5, 2], hatch='//', linewidth=0, color='b')
axs[3].set_title('linewidth=0')
plt.show()

Upvotes: 0

Markus Schmidgall
Markus Schmidgall

Reputation: 126

Here are 2 links that probably can help you with your problem.

https://community.plotly.com/t/how-to-remove-the-white-border-from-bar-marker/41724/2

How to remove white lines around bars using plotly.express.bar?

  • need to set marker_line_width

Upvotes: 0

Related Questions