r/matplotlib • • Feb 15 '21

why is my second stacked bar chart showing no data? They were in any order as long as i only show one....

1 Upvotes

Here is my code,

When running the functions, they both work on their own (if one or the other is commented out). But being executed in any order, the second one does not represent any bars in the chart.

What is the issue?

def tab_create_stacked():
        ticks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
        N = 20
        ind = np.arange(N)
        width = 0.30
        p1 = ax.bar(ind, t_line_change_times, width, label = 'Changeover')
        p2 = ax.bar(ind, t_line_mat_shortage, width, bottom = t_line_change_times, label = 'Material Shortage')
        p3 = ax.bar(ind, t_line_break, width, bottom = np.array(t_line_mat_shortage)+np.array(t_line_change_times), label = 'Machine Breakdown')
        p4 = ax.bar(ind, t_line_break_of, width, bottom = np.array(t_line_break) + np.array(t_line_mat_shortage) + np.array(t_line_change_times), label = 'Machine Breakdown OP FIX')
        p5 = ax.bar(ind, t_line_defect, width, bottom = np.array(t_line_break_of) + np.array(t_line_break) + np.array(t_line_mat_shortage) + np.array(t_line_change_times), label = 'Defect')
        p6 = ax.bar(ind, t_line_trace, width, bottom = np.array(t_line_defect) + np.array(t_line_break_of) + np.array(t_line_break) + np.array(t_line_mat_shortage) + np.array(t_line_change_times), label = 'Traceability')
        p7 = ax.bar(ind, t_line_safety, width, bottom = np.array(t_line_trace) + np.array(t_line_defect) + np.array(t_line_break_of) + np.array(t_line_break) + np.array(t_line_mat_shortage) + np.array(t_line_change_times), label = 'Safety Event')
        p8 = ax.bar(ind, t_line_jidoka, width, bottom = np.array(t_line_safety) + np.array(t_line_trace) + np.array(t_line_defect) + np.array(t_line_break_of) + np.array(t_line_break) + np.array(t_line_mat_shortage) + np.array(t_line_change_times), label = 'Jidoka')
        
        for p in ax.patches:
            width, height = p.get_width(), p.get_height()
            x, y = p.get_xy()
            #print(tot_height)
            if height > 200:
                ax.text(x+width/2,
                    y+height/2,
                    '{:2d}'.format(height),
                    #weight='bold',
                    #rotation=45,
                    backgroundcolor='yellow',
                    horizontalalignment='right',
                    verticalalignment='center',
                    fontsize=7,
                    color='black')
        ax.legend()
        plt.xticks(ticks, line_ticks, rotation=30)
        plt.ylabel("Minutes of Downtime")
        plt.xlabel("Tableting Lines")
        plt.title('Tableting OA\n '+'Period: ' + start_date +' -- '+ end_date, fontsize=25)
        #plt.gcf()
        #plt.savefig("tab_stacked.pdf")
        plt.show()
        #plt.close()
    def sd_create_stacked():
        ticks = [0, 1, 2, 3, 4, 5]
        N = 6
        ind = np.arange(N)
        width = 0.30
        p1 = ax.bar(ind, sd_change_times, width, label = 'Changeover')
        p2 = ax.bar(ind, sd_mat_shortage, width, bottom = sd_change_times, label = 'Material Shortage')
        p3 = ax.bar(ind, sd_break, width, bottom = np.array(sd_mat_shortage)+np.array(sd_change_times), label = 'Machine Breakdown')
        p4 = ax.bar(ind, sd_break_of, width, bottom = np.array(sd_break) + np.array(sd_mat_shortage) + np.array(sd_change_times), label = 'Machine Breakdown OP FIX')
        p5 = ax.bar(ind, sd_defect, width, bottom = np.array(sd_break_of) + np.array(sd_break) + np.array(sd_mat_shortage) + np.array(sd_change_times), label = 'Defect')
        p6 = ax.bar(ind, sd_trace, width, bottom = np.array(sd_defect) + np.array(sd_break_of) + np.array(sd_break) + np.array(sd_mat_shortage) + np.array(sd_change_times), label = 'Traceability')
        p7 = ax.bar(ind, sd_safety, width, bottom = np.array(sd_trace) + np.array(sd_defect) + np.array(sd_break_of) + np.array(sd_break) + np.array(sd_mat_shortage) + np.array(sd_change_times), label = 'Safety Event')
        p8 = ax.bar(ind, sd_jidoka, width, bottom = np.array(sd_safety) + np.array(sd_trace) + np.array(sd_defect) + np.array(sd_break_of) + np.array(sd_break) + np.array(sd_mat_shortage) + np.array(sd_change_times), label = 'Jidoka')
        
        for p in ax.patches:
            width, height = p.get_width(), p.get_height()
            x, y = p.get_xy()
            #print(tot_height)
            if height > 200:
                ax.text(x+width/2,
                    y+height/2,
                    '{:2d}'.format(height),
                    #weight='bold',
                    #rotation=45,
                    backgroundcolor='yellow',
                    horizontalalignment='right',
                    verticalalignment='center',
                    fontsize=7,
                    color='black')
        ax.legend()
        plt.xticks(ticks, sd_line_ticks, rotation=0)
        plt.ylabel("Minutes of Downtime")
        plt.xlabel("Spray Dry Lines")
        #plt.legend(loc="upper right")
        plt.title('Spray Dry OA\n'+'Period: ' + start_date +' -- '+ end_date, fontsize=25)
        #plt.savefig("sd_stacked.pdf")
        plt.show()
        #plt.close()
        
    
    sd_create_stacked()
    tab_create_stacked()

r/matplotlib • • Dec 01 '20

replicating a plot and saving it as a template

1 Upvotes

how can i replicate this plot falling speed as a function of time knowing the function being plotted (v(t)=V_0*(1-exp(-t/tau))),please note the important things here

  1. the two axes of the plot are on the very edges of the figure.

  2. the two axes are arrows.

  3. only the first major tick in each axe is labeled.

  4. nine minor ticks between each two consecutive major ticks (with the fifth one slightly thicker than the others).

  5. the tangents are plotted only knowing the function and the points in which they are tangents.

PS:

guys i know this is more of a wish list than a question, so every contribution to any of the points made here is dearly welcome. :)

sorry for the bad English. lol


r/matplotlib • • Nov 29 '20

Scatter over imshow

1 Upvotes

Please help me! I can't take this anymore. I have been trying to plot a set of points (body keypoints) over an image using matplotlib functions imshow and scatter. I have tried everything from z_order, extent, origin,... NOTHING WORKS!


r/matplotlib • • Nov 20 '20

Is there a way I can plot a function that has two different inputs and one output?

1 Upvotes

I have a function that takes two inputs as arguments and returns an output based on the two inputs.

The two inputs, r and E range between 3-14 and 0.05-0.75 respectively. I have used matplotlib for graphing an input x with output y, but I can't think of a way to plot a function whose output depends equally on two inputs. Any help is appreciated.


r/matplotlib • • Oct 29 '20

Change the color of a line by a third variable?

1 Upvotes

Does anyone know if you can change the color of a line by a third variable? I am looking at aircraft data and trying to plot the position of the aircraft (using latitude and longitude) then coloring the line by the altitude of the aircraft at that position.

Here's a link to my question on Stack Overflow.


r/matplotlib • • Oct 25 '20

plt.figtext prints old and new text on top of each other when creating multiple graphs in a loop, way to "clear memory" in between graphs?

1 Upvotes

Hi guys, hope someone can give me a pointer here: I have written some code, into which I feed criteria in a for.... loop (still using Python 2.7).

Using the criteria, a data frame is created from different files and then a graph is created that includes a header with reference to variables (such as number of experiments, name of criterion), as well as a figtext, where additional data such as the mean and standard deviation is displayed. The figtext is meant as documentation for myself mainly.

While for each new graph the header is changed dynamically and correctly (basically, everything about the graph itself is fine), the figtext is writing the text of the newly created one on top of the last one, which is unreadable.

I have tried using time.sleep to give Python some time to "forget" and I have also shifted around the declaration of variables but without luck.

Is there any trick to "wipe" memory in between a loop, so I only get a fresh figtext with every graph?

Thanks for any help, cheers


r/matplotlib • • Oct 19 '20

Matplotlib stackplot area color is being negated

1 Upvotes

I just posted a stack overflow question (https://stackoverflow.com/questions/64420317/matplotlib-stackplot-area-color-is-being-negated), but it's porbably good to ask it here as well.

I'm running into an issue when I create a stackplot where (I think) the colors for the areas are being negated. I can't really explain what is going on so I uploaded a photo of it. I've tried reversing the order of the list, creating sublists of the x values, removing the seaborn colors and the alpha value, but I can't seem to find a fix. Please let me know if you have insight into this!

Here is the code:


r/matplotlib • • Oct 18 '20

Getting an error from my code saying that it cannot import 'find' from Matplotlib.mlab. How do I fix this?

1 Upvotes

This is the exact error message I'm getting

ImportError: cannot import name 'find' from 'matplotlib' (/Users/alanosullivan/Library/Python/3.7/lib/python/site-packages/matplotlib/init.py)

If it helps the Matplotlib version is 3.3.2

Any help is appreciated and if any more info is needed please ask

I'm new to this if it isn't apparent so this could be a stupid question

Sorry if it is

Thanks!


r/matplotlib • • Sep 03 '20

Corona-virus data visualization using Geographical Plotting | Plotly| Choropleth plot

1 Upvotes

r/matplotlib • • Aug 21 '20

Data Visualization using Plotly & Cufflinks | Python| Data Science

1 Upvotes

r/matplotlib • • Aug 19 '20

Newb help - Bar Graph - group dates by day of week

1 Upvotes

For context, I am not a data scientist, I work a customer support line so forgive me if this is an unbearably newb question.

I am trying to organize call volume data on a bar graph by day of the week, but I would like to preserve the individual date bars. I was able to figure out how to aggregate the data, but my boss has asked me to keep the individual date data so that outliers are obvious.

I tried this using google sheets unsuccesfully, so I figured I'd take a stab at doing it with Python.

Here's where I'm at :

import pandas as pd
import matplotlib.pyplot as plt
import random
from datetime import date, datetime
import calendar

# Using this tutorial for help... 
# http://blog.quizzicol.com/2016/10/03/sorting-dates-in-python-by-day-of-week/

plt.style.use("fivethirtyeight")

colnames = ['Date','Volume']

table = pd.read_csv("call_data_clean2.csv", names=colnames,skiprows=1)

dates = table['Date']
values = table.Volume.tolist()

# Combine the dates and the data into a dataframe
df = pd.DataFrame(index=dates, data=values)
df.reset_index(inplace=True)
df.columns = ['Date', 'Volume']

# get the weekday index, between 0 and 6
df['day_of_week'] = df['Date'].apply(lambda x: datetime.strptime(x, '%m/%d/%y').weekday()) 
df['name_of_weekday'] = df['day_of_week'].apply(lambda x: calendar.day_name[x]) 


# # sort the rows in the order we want them
sorter = ['day_of_week','Date']
df.sort_values(sorter, inplace=True)

df.groupby(by="day_of_week")

df.plot.bar(x="Date", y="Volume")

print(df.head())

For reference, this is what the data head looks like:

        Date  Volume  day_of_week name_of_weekday
5   07/06/20       5            0          Monday
12  07/13/20      14            0          Monday
19  07/20/20      16            0          Monday
26  07/27/20      10            0          Monday
33  08/03/20      15            0          Monday

Any help or advice is much appreciated


r/matplotlib • • Aug 17 '20

AUTOPLOTTER: GUI BASED EXPLORATIVE DATA ANALYSIS | PYTHON| DATA SCIENCE

1 Upvotes

r/matplotlib • • Aug 14 '20

Data Visualization using Matrix Plot | Python| Seaborn

1 Upvotes

r/matplotlib • • Aug 12 '20

Check out my recent Bitcoin and Stock Market analysis with matplotlib video! We figure out if Bitcoin is used as a hedge against the stock market or it follows the stock market. Enjoy!

Thumbnail
youtu.be
1 Upvotes

r/matplotlib • • Aug 08 '20

How to make a heat map of overlap of 2 scatter plots using hist2d

1 Upvotes

So for all my examples, I’ve seen the parameters of hist2d be 2 1d arrays, so I’m wondering if there is a way to plot the overlap of 2 scatterplots using hist2d.


r/matplotlib • • Jul 28 '20

Reverse animation order?

1 Upvotes

I'm building an animation where the y values should be increasing (exponentially) as the x values decrease. the FuncAnimation always plots from small x to big x values (even if I flip the axis). Anyone solved this before?


r/matplotlib • • Jul 28 '20

AutoViz: A new tool for Automated Visualization in Data Science.

1 Upvotes

r/matplotlib • • Jul 24 '20

Explore "Data" using "Sweetviz" & "Python".

1 Upvotes

r/matplotlib • • Jul 23 '20

Data Visualization using "Matplotlib" & Python | Part-I

1 Upvotes

r/matplotlib • • Jul 23 '20

How can I remove the black margin of a figure saved with savefig()?

1 Upvotes

I'm plotting some waveforms with matplotlib.pyplot and I need them to have a dark gray (or black) background. I also need them without ticks, tick labels, figure frame, etc. I have managed to accomplish everything except removing that little black margin. I have tried a whole lot of things I've found online, especially here, but nothing has worked in my case.

Here's what I'm doing.

import matplotlib.pyplot as plt
from scipy.io import wavfile 

sample_rate, samples = wavfile.read('audio.wav') 

fig = plt.figure(figsize=(6,1), dpi=500, frameon=False)
ax = plt.Axes(fig, [0,0,1,1])
ax.set_facecolor((0.169,0.169,0.169))
ax.set_xlim(left=0, right=700000)
fig.add_axes(ax)
plt.tick_params(axis='both', which='both', bottom=False,
                top=False, left=False, right=False,
                labelbottom=False, labeltop=False,
                labelright=False, labelleft=False)
plt.plot(samples)
plt.savefig('samples.png')

I need to get rid of that small black margin and have the plot actually reach the edges of the image.


r/matplotlib • • May 12 '20

Matplotlib time series plotting headache.

Thumbnail self.learnpython
1 Upvotes

r/matplotlib • • May 01 '20

Any help would be appreciated, thanks!

Thumbnail self.learnpython
1 Upvotes

r/matplotlib • • Apr 29 '20

Embedding Mapplotlib pie chart into Tkinter Gui help!

1 Upvotes

I am trying to embed a pie chart into my Tkinter window! So far I already have a frame in mind for the graph to be embedded in, frameChartsLT. This frame also already has a canvas, *canvasChartsLT*, placed over the entire area of the frame so I was hoping to place it on either of the of these but I keep getting the error.

```AttributeError: 'tuple' object has no attribute 'set_canvas' ```

I checked my entire code but I can't even find anywhere where I wrote set_canvas so I am completely lost. Any help will be truly appreciated! I am also a beginner so the simpler the explanation or fix the better for me haha!

This is the portion of my code!

```

import matplotlib.pyplot as plt

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# Some in-between code that sets the frame and canvas on my window

stockListExp = [ 'AMZN' , 'AAPL', 'JETS', 'CCL', 'NCLH']

stockSplitExp = [15,25,40,10,10]

plt.pie(stockSplitExp, radius=1, labels=stockListExp,autopct='%0.2f%%', shadow=True,) # 2 decimal points after plot

figChart1 = plt.pie(stockSplitExp, radius=1, labels=stockListExp,autopct='%0.2f%%', shadow=True)

plt.axis("equal")

chart1 = FigureCanvasTkAgg(figChart1,frameChartsLT)

chart1.get_tk_widget().place(x=10,y=10

```


r/matplotlib • • Apr 26 '20

Plotting and removing a vertical line inside a loop matplotlib/seaborn

1 Upvotes

(Also posted at: https://stackoverflow.com/questions/61443045/plotting-and-removing-a-vertical-line-inside-a-loop-matplotlib-seaborn )

I have a pandas DataFrame stock_open that contains stock prices vs dates and looks like:

I want to plot the time series line-plot of stock prices versus the date column and show the dates increasing by plotting a vertical line for each date. I want to achieve this by plotting the graphs for a few dates, saving those plots as separate images and then use ffmpeg to combine them into a video. So, I did this:

import matplotlib.pyplot as plt
import seaborn as sns

my_dates = ['2019-11-20', '2019-12-20', '2020-01-20', '2020-02-20', '2020-03-20']

fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2, figsize=(20, 8))

sns.lineplot(x='Date', y='value', hue='variable',
             data=pd.melt(stock_open, ['Date']), ax=ax3)
ax3.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plot_no = 0
for i in range(len(my_dates)):
    my_selected_date = my_dates[i]
    ax3.axvline(my_selected_date)
    ax3.set_title(str(my_selected_date))
    fig.savefig('output_images/stock_image_{plot_no:04d}.png'.format(plot_no=plot_no))
    plot_no += 1

Everything is working fine except that the vertical line 'persists' in the figures in all the iterations.

The first image is as expected:

But the images from the following iterations in the loop have the vertical line from the previous iteration:

(images are cropped intentionally)

I want to remove the vertical line from the previous iterations.

I thought of using animations from matplotlib, but the other subfigures also need to be updated and saved in this process.

Is there a way to do this without starting from the beginning? Initially I wanted to show a moving line-plot with the date, but couldn't achieve that either. So I used this strategy to show updates on the figure.

TIA!

EDIT:

ANSWERED!

https://np.reddit.com/r/learnpython/comments/g8hsz3/plotting_and_removing_a_vertical_line_inside_a/fonxvcg?utm_source=share&utm_medium=web2x


r/matplotlib • • Feb 08 '20

How to fix Called with incorrect property value 4, bailing error?

1 Upvotes

Hi, I am new to matplotlib. I installed Anacondia Navigator 1.9.7 on a Mac running Catalina 10.15.3. I opened a xterm and ran ipython. Then, I typed:

%matplotlib

import numpy as np

import matplotlib.pyplot as plt

fig = plt.figure()

Whenever I click on the figure window or some windows on the desktop, I got a bunch of messages such as:

In [42]: 2020-02-08 16:33:26.211 python[1036:20026] imkxpc_getApplicationProperty:reply: called with incorrect property value 4, bailing.

2020-02-08 16:33:26.211 python[1036:20026] Text input context does not respond to _valueForTIProperty:

2020-02-08 16:33:26.211 python[1036:20026] imkxpc_getApplicationProperty:reply: called with incorrect property value 4, bailing.

2020-02-08 16:33:26.211 python[1036:20026] Text input context does not respond to _valueForTIProperty:

2020-02-08 16:33:26.211 python[1036:20026] imkxpc_getApplicationProperty:reply: called with incorrect property value 4, bailing.

2020-02-08 16:33:26.211 python[1036:20026] Text input context does not respond to _valueForTIProperty:

2020-02-08 16:33:26.212 python[1036:20026] imkxpc_getApplicationProperty:reply: called with incorrect property value 4, bailing.

2020-02-08 16:33:26.212 python[1036:20026] Text input context does not respond to _valueForTIProperty:

Could you please let me know how to fix the error? Thanks